Trying to figure out how to write a custom matcher for a primitive value. Say I’ve got the following custom matcher:
class IsEven extends ArgumentMatcher<Integer> {
public boolean matches(Object i) {
return ((Integer) i) % 2 == 0;
}
}
And I run the following test. ‘mocked’ is an already-mocked instance of a class that has a method ‘someMethod’:
@Test
public void primatives() {
mocked.someMethod(2);
ArgumentMatcher<Integer> customMatcher = new IsEven();
// ! Throws NPE !
Mockito.verify(mocked).someMethod(Mockito.argThat(customMatcher));
}
The reason for the NullPointerException is that the Mockio.argThat method always returns a null, which I’m guessing cannot be autoboxed back into an integer.
I feel as though this woudl be a common use case – any advice?
Thanks,
Roy
.. Reading Javadoc helps:
In rare cases when the parameter is a primitive then you must use relevant intThat(), floatThat(), etc. method. This way you will avoid NullPointerException during autounboxing.