4

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)
Izaya
  • 1,270
  • 2
  • 13
  • 31
  • Please add the **complete error message** and a [Minimal, Complete, and Verifiable example](/help/mcve). – Timothy Truckle May 25 '21 at 12:55
  • Have you read through this: https://stackoverflow.com/questions/52139619/simulation-of-service-using-mockito-2-leads-to-stubbing-error ? – ernest_k May 25 '21 at 12:55
  • Yes, I haven't tried this because I really wish to keep a high Strictness for my tests. – Izaya May 25 '21 at 12:59
  • You should attach a code where you are invoking method `myMethod` – Alex May 25 '21 at 12:59
  • It seems it's coming from `any(HttpServletRequest.class)`. I've tried to change `myMethod` to take only one argument which is `HttpServletRequest request`. In the method I'm testing I simply call it by `myObject(request)`. I've updated my question. – Izaya May 25 '21 at 15:08
  • 1
    1. `myMethod` or `todo` method!;)? 2. `any(Class clazz)` [*doesn't match* `null`](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html#any-java.lang.Class-) ! (-> `request == null`?;) – xerx593 May 25 '21 at 15:30
  • Thanks a lot, it was because my value was null and `any()` was not working on null arguments. – Izaya May 25 '21 at 15:49

1 Answers1

6

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.

Izaya
  • 1,270
  • 2
  • 13
  • 31
  • 1
    There is a new `isNull` ArgumentMatcher too that would fix this this, as noted `any` is for non-null parameters, `isNull` is now for null params – Darren Forsythe May 25 '21 at 16:21