javamockitostub

Mockito 3 any() Strict stubbing argument mismatch


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)

Solution

  • 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.