I've spent the last little while pulling out my hair trying to find the problem in my test, and eventually figured out it has to do with mocking a method that takes primitive arguments. Here's a sample test that demos the problem:
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Test;
public class MockitoTest {
public static interface Foo {
public Object causeProblems(long arg);
}
@Test
public void testFoo() {
Foo foo = mock(Foo.class);
foo.causeProblems(123);
verify(foo, times(1)).causeProblems(any());
}
}
When running this test (I'm using Mockito 1.10 and Java8), and for some reason my stack trace is showing an NPE on the verify
line:
java.lang.NullPointerException
at com.amazon.jetstream.executor.worker.invoke.MockitoTest.testFoo(MockitoTest.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
....
I think part of my stack trace is being suppressed (?) Digging into it a bit further, I can get slightly more info out of it if I run it in Eclipse and "inspect" the line, which tells me simply:
java.lang.NullPointerException at longValue()
Questions:
Will This Library Help Overcoming Nullpointerexceptions With Mockito. any()? Answer : Passing Mockito.
@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @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.
Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call. Use doAnswer() when you want to stub a void method with generic Answer .
Configure Mockito for Final Methods and ClassesBefore we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.
You should matcher that matches long not any object:
verify(foo, times(1)).causeProblems(anyLong());
I checked that it runs correctly.
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