I'm trying to mock a method that creates a local variable, tries something, and does logging if an exception is thrown. Here's a snippet of code:
public void myFunction() {
//Some stuff
try {
new File("foo").getAbsoluteFile();
} catch (SecurityException e) {
//Do some logging
}
}
I'd like to mock this logging behavior using JMockit (using version 1.8 if it matters). So I created the following test:
@Test(expected=SecurityException.class)
public void testAbsoluteFile(
@Injectable final File file
) throws IOException {
new Expectations(File.class){{
new File(anyString);
result = file;
file.getAbsoluteFile();
result = new SecurityException();
}};
myFunction();
}
The trouble is that this seems to give me a NullPointerException
on the inner workings of File.getAbsoluteFile()
, which I find absolutely bizarre:
java.lang.Exception: Unexpected exception, expected<java.lang.SecurityException> but was<java.lang.NullPointerException>
Caused by: java.lang.NullPointerException
at java.io.Win32FileSystem.slashify(Win32FileSystem.java:56)
at java.io.Win32FileSystem.resolve(Win32FileSystem.java:330)
at java.io.File.getAbsolutePath(File.java:556)
at java.io.File.getAbsoluteFile(File.java:572)
at com.vue.rescoreservice.ExpectationTest.myFunction(ExpectationTest.java:39)
at com.vue.rescoreservice.ExpectationTest.testAbsoluteFile(ExpectationTest.java:33)
This seems really bizarre as it's saying that a local variable in the Win32FileSystem
class (an internal class not in the typical Java API) is throwing a NullPointerException, when it never did before.
The lines that are in the stack trace are as follows:
//In myFunction()
new File("foo").getAbsoluteFile();
and
//In testAbsoluteFile()
myFunction();
Why is this happening? And how can I make it so that JMockit does not throw a NullPointerException on local variables of internal classes?