I’ve written the following JUnit test, which uses ArgumentMatchers.
MyClass classUnderTest = new MyClass();
class AnyBooleanMatcher extends ArgumentMatcher<Boolean> {
public boolean matches(Object argument) {
return ((Boolean) argument).equals(Boolean.TRUE);
}
}
class MyObjectMatcher extends ArgumentMatcher<MyObject> {
public boolean matches(Object argument) {
return ((MyObject) argument).getValue().equals("123");
}
}
final Service mockService = mock(Service.class);
when(mockService.search(Matchers.argThat(new MyObjectMatcher()),
Matchers.argThat(new AnyBooleanMatcher())));
classUnderTest.callMethod(mock(ActionEvent.class));
verify(mockService).search(Matchers.argThat(new MyObjectMatcher()),
Matchers.argThat(new AnyBooleanMatcher()));
Unfortunately I’m always getting a NullPointerException, at the when statement.
I even know why: argThat returns null, as specified in the JavaDoc. But I don’t know why my test won’t work, when the ones in the example – which are modelled in exactly the same way – do work.
You have a
NullPointerExceptionbecause the method signature is using a native type, and you are usingMatchers.argThat, which returns an object.When compiled Javac will add auto-unboxing code around
Matchers.argThat(new AnyBooleanMatcher()), as you said it returnsnull, so you have the cause of the NPE.I’m pretty sure the Javadoc of mockito also say to use
intThat,booleanThatstyle method when dealing with native types. Using those will prevent the auto-unboxing code introduced by the compiler.On another topic, I would recommand you to write code like that, in order to make it more readable.