문제

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.

도움이 되었습니까?

해결책

You need to define the behavior for getPath() for folder as it gets called internally in File class.

You can do it as:

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

It will work only till you don't really create a new file but only calling new File.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top