Reputation: 1568
I'm using Mockito 3.1.0.
I'm trying to Mock my method with this syntax:
when(mockedObject.myMethod(any(HttpServletRequest.class)).thenReturn(1);
myMethod
is simply:
public Integer myMethod(HttpServletRequest request) {
return 0;
}
In the method I'm testing it's simply called by:
int r = myObject.myMethod(request);
But I'm getting:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'myMethod' method:
mockedObject.myMethod(null);
-> at somefile.java:160)
- has following stubbing(s) with different arguments:
1. mockedObject.myMethod(null);
-> at somefileTest.java:68)
Upvotes: 8
Views: 29321
Reputation: 150
In my case, method's arguments are not matching with the actual method. Yes, you can use any but that is not a good practice. You should explicitly use the argument that you are using in the actual method.
Upvotes: 0
Reputation: 1035
You can use nullable(MyClass.class)
to accept either null
or given type.
This is the earliest appearance I think (v2.5.0), but is also available in Mockito 3, and in the latest (v5.8.0)
However, it is unlikely that you have unused HttpServletRequest request
, so to avoid NullPointerException, you may want to mock it instead of allowing it to be nullable in the Test.
Upvotes: 0
Reputation: 1568
As explained here any(myClass)
doesn't work if the provided argument is null, only any()
does as explained here. In my case, request
was null so any(HttpServletRequest.class)
couldn't catch it.
I fixed it by changing
when(mockedObject.myMethod(any(HttpServletRequest.class)).thenReturn(1);
to this if you are sure it will be null
when(mockedObject.myMethod(null)).thenReturn(1);
or to this if you want to catch all cases
when(mockedObject.myMethod(any())).thenReturn(1);
Another method is to use ArgumentMatchers
:
when(mockedObject.myMethod(ArgumentMatchers.<HttpServletRequest>any())).thenReturn(1);
Thanks @xerx593 for the explanation.
Upvotes: 10