Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito for int primitive

Tags:

java

mockito

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.

like image 476
user3278325 Avatar asked Feb 24 '14 06:02

user3278325


People also ask

How do you mock a primitive type?

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.

What is eq() in Mockito?

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.

What does thenReturn do in Mockito?

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").

How Mockito works internally?

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.


2 Answers

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.

like image 57
Jeff Bowman Avatar answered Sep 17 '22 12:09

Jeff Bowman


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,

like image 39
Ketan Avatar answered Sep 21 '22 12:09

Ketan