10

I'm creating a File mock object with Mockito that will be used as the directory to store a new File.

Folder folder = Mockito.mock(File.class);
File file = new Agent().createNewFile(folder, "fileName");

and inside my Agent class:

public File createNewFile(File folder, String filename){
    return new File(folder, "testfile");
}

But I'm getting a NullPointerException at the initialization block of File when creating the new file inside createNewFile method:

java.lang.NullPointerException at java.io.File.<init>(File.java:308)

I think it happens because File doesn't have any empty constructor, so when mocking the object some internal state remains null.

Am I taking the wrong approach mocking the File folder object? My goal is to check some constraints before creating the new file, but I don't want to depend on an existing real folder on the file system.

Thank you.

4

1 に答える 1

9

File クラスで内部的に呼び出されるため、フォルダーの getPath() の動作を定義する必要があります。

次のように実行できます。

File folder = Mockito.mock(File.class);
when(folder.getPath()).thenReturn("C:\temp\");
File file = new Agent().createNewFile(folder, "fileName");

実際に新しいファイルを作成せず、新しいファイルを呼び出すまでのみ機能します。

于 2010-08-18T18:02:11.783 に答える