Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mix Argument Captor and a regular matcher?

I need to verify a method with multiple parameter in Mockito, but need to capture only one argument, the others I need only a simple matcher. Is that possible?

For instance, if I have:

@Mock
private Map<K,V> mockedMap;
...
ArgumentCaptor<K> argument = ArgumentCaptor.forClass(K.class);
verify(mockedMap).put(argument.capture(), any(V.class));

In this case do I need to write a captor for each argument in spite of the fact I need to capture only the first argument?

like image 414
kavai77 Avatar asked Sep 22 '15 12:09

kavai77


People also ask

What can I use instead of Mockito matchers?

org. mockito. Matchers is deprecated, ArgumentMatchers should be used instead.

What is ArgumentCaptor used for?

ArgumentCaptor allows us to capture an argument passed to a method to inspect it. This is especially useful when we can't access the argument outside of the method we'd like to test.

Can the Mockito Matcher methods be used as return values?

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.


1 Answers

In this case do I need to write a captor for each argument in spite of the fact I need to capture only the first argument?

durron597's answer is correct—you do not need to capture all arguments if you want to capture one of them. One point of clarification, though: a call to ArgumentCaptor.capture() counts as a Mockito matcher, and in Mockito if you use a matcher for any method argument you do have to use a matcher for all arguments.

For a method yourMock.yourMethod(int, int, int) and an ArgumentCaptor<Integer> intCaptor:

/*  good: */  verify(yourMock).yourMethod(2, 3, 4);  // eq by default
/*  same: */  verify(yourMock).yourMethod(eq(2), eq(3), eq(4));

/*   BAD: */  verify(yourMock).yourMethod(intCaptor.capture(), 3, 4);
/* fixed: */  verify(yourMock).yourMethod(intCaptor.capture(), eq(3), eq(4));

These also work:

verify(yourMock).yourMethod(intCaptor.capture(), eq(5), otherIntCaptor.capture());
verify(yourMock).yourMethod(intCaptor.capture(), anyInt(), gt(9000));
like image 112
Jeff Bowman Avatar answered Sep 27 '22 22:09

Jeff Bowman