Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock File class and NullPointerException

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.

like image 890
manolowar Avatar asked Aug 18 '10 17:08

manolowar


People also ask

Why is mock returning NULL?

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.

What is the difference between @InjectMocks and @mock?

@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.

What is the difference between doReturn and thenReturn?

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 .


1 Answers

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.

like image 189
Ankit Bansal Avatar answered Sep 17 '22 18:09

Ankit Bansal