3

I am new with testing. I have tried this but got an exception.

@Mock
private Context context;    
...
when(service.getResult(any(), context)).thenReturn(new ArrayList<>());

Exception:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:

Matheus Lacerda
  • 5,983
  • 11
  • 29
  • 45
kamboj
  • 411
  • 1
  • 9
  • 18

2 Answers2

9

Mockito.any() is a Mockito argument matcher. As you specify it in one of the parameters defined in a mock recording, you have to use argument matcher for all parameters.
Mockito.eq(T) is the way to transform any parameter into a argument matcher.
So this should be fine :

@Mock
private Context context;    

@Mock
private Service service; 
...
when(service.getResult(any(), eq(context)).thenReturn(new ArrayList<>());
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 1
    Probably a duplicate, but a nice precise answer. So who am I to worry :-) – GhostCat Apr 28 '18 at 09:47
  • 1
    And well, nobody beats Jon Skeet. He occasionally allows us to think that to encourage us! – GhostCat Apr 28 '18 at 09:48
  • @GhostCast I like well your theory on the kindness of Jon toward us :) – davidxxx Apr 28 '18 at 17:55
  • I probably only saw .05 % of all the content he put up here, but I think he is one of the most "nice guys" I ever saw on online boards. A role model on many levels. – GhostCat Apr 28 '18 at 18:08
  • I called you : GhostCast ! Sorry :) I agree totally about Jon. A very very nice person. Long life to him ! – davidxxx Apr 28 '18 at 19:22
1

Similar question has been asked many times. I think the best answer is here:

Mockito requires you to either use only raw values or only matchers when stubbing a method call. The full exception (not posted by you here) surely explains everything.

Invalid use of argument matchers

Rostislav V
  • 1,706
  • 1
  • 19
  • 31