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.
If a method return type is a custom class, a mock returns null because there is no empty value for a custom class. RETURN_MOCKS will try to return mocks if possible instead of null . Since final class cannot be mocked, null is still returned in that case.
@Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.
One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test. I strongly recommend only using doReturn/when .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With