1

I have two custom ArgumentMatchers and I'd like my mock to return a different value based on the argument value.

Example:

when(myMock.method(new ArgMatcher1()).thenReturn(false);
when(myMock.method(new ArgMatcher2()).thenReturn(true);

Unfortunately, the second call to when() results in an exception. This makes sense to me because, if the argument matches both ArgumentMatchers, Mockito wouldn't know whether to return true or false. Is there a way to do this in Mockito? It could even be something like:

when(myMock.method(new ArgMatcher2()).thenReturn(false).elseReturn(true);
Chris Morris
  • 4,335
  • 4
  • 24
  • 28
  • 1
    See http://stackoverflow.com/questions/13846837/using-multiple-argumentmatchers-on-the-same-mock?rq=1. – Chris Morris Mar 08 '13 at 21:00
  • 1
    You absolutely can have two different matchers work with Mockito. What is the exception? What do ArgMatcher1 and ArgMatcher2 do? – jhericks Mar 09 '13 at 01:29
  • I found a better way to do what I needed to, so I'm no longer pursuing this option. – Chris Morris Mar 09 '13 at 02:52
  • 1
    Possible duplicate of [Using Multiple ArgumentMatchers on the same mock](http://stackoverflow.com/questions/13846837/using-multiple-argumentmatchers-on-the-same-mock) – Captain Man Mar 10 '17 at 15:34

3 Answers3

0

I'm not sure how your matchers are coded, but having two different matchers is supported of course, maybe the method you are stubbing is not mockable via Mockito (final).

Also for the record it is possible to tell the stub to return different return values in different ways :

when(myMock.method(new ArgMatcher2()).thenReturn(false, false, true).thenReturn(true);
bric3
  • 40,072
  • 9
  • 91
  • 111
0

If you're interested in returning a default value from Mockito, then this I have achieved like that:

when(myMock.myMethod(any())).thenReturn(true);
when(myMosk.myMethod("some other argumetn")).thenReturn(true);

Will it help you? Hard to say, I haven't used matchers the way you do with new keyword. It might be, that Mockito doesn't understand that well your custom matchers.

Lauri
  • 1,859
  • 2
  • 14
  • 17
0

Switch to syntax:

doAnswer(args->false).when(myMock).myMethod(any());
iskramac
  • 868
  • 6
  • 14