If I am using a Wrapper class type variable as argument Mockito test case is getting pass but, how to write Mockito test case for int primitive type variable which is an argument to a method in ServiceImpl.
Mock a primitive If you just use the simple syntax of jest. mock('./greeter') to mock out the whole file, you'll find that the primitive values remain untouched.
Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method. when(mockFoo. bool(eq("false"), anyInt(), any(Object.
thenReturn or doReturn() are used to specify a value to be returned upon method invocation. //”do something when this mock's method is called with the following arguments” doReturn("a").
Mockito was released as an open-source testing framework under the MIT (Massachusetts Institute of Technology) License. It internally uses the Java Reflection API to generate mock objects for a specific interface. Mock objects are referred to as the dummy or proxy objects used for actual implementations.
You may have some trouble with any
or argThat
for primitive-type arguments to when
and verify
. Those Object-centric methods do their work with side-effects correctly, but they tend to return null
for a dummy return value, which doesn't work for Java unwrapping primitives via auto-boxing.
Luckily, the org.mockito.ArgumentMatchers
class has a full complement of primitive-centric methods (of which I've listed the int
methods here):
static int anyInt() static int eq(int value) static int intThat(org.hamcrest.ArgumentMatcher<java.lang.Integer> matcher)
See all of them at the documentation for the ArgumentMatchers class.
I know that the question has been more than 4 years and 8 months old but for the sake of clear solution as of today, I am posting this
In my case, the method signature to be tested is
public SomeObject create(String code, int status)
so the test code for verifying the argument values when the method was invoked would be following
verify(this.service).create( argThat(code -> "dummy_code".equals(code)), intThat(status -> status == 105));
If I go with the argThat even for int (or any primitive types) then mockito throws NPE
Currently I am using org.mockito:mockito-core:jar:2.15.0 which must have been advanced considering the time when the question was asked! But thinking that this might be helpful to people... Thanks,
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