Reputation: 1904
I have a class A that has to make two subsequent calls to a method of its dependency B that takes a collection as an argument:
class A{
private B myDependency;
public myClassMethod() {
// ... on more than one occasion calls myDependency.dependencyMehtod(someColleciton);
}
}
class B{
public void dependencyMehtod(Collection<Something> input)
}
I would like to write a unit test for class A (preferably using Mockito) that verifies that the dependency method was called exactly a given number of times and also verify the size of the input Collection at each subsequent invocation (the size of the argument varies between calls). How would I do that?
I tried using
myAObject.myClassMethod();
verify(myMockOfB).dependencyMehtod((Collection<Something>) argThat(hasSize(3)); //I expect a size of 3 on the first call
verify(myMockOfB).dependencyMehtod((Collection<Something>) argThat(hasSize(1)); //I expect a size of 1 on the second call
However, I get an error message from Mockito that A collection of size 1 was found where a collection of size 3 was expected. What am I doing wrong?
Upvotes: 0
Views: 1147
Reputation: 2230
You can use ArgumentCaptor
. Here is an example:
@Captor
private ArgumentCaptor<Collection<Something>> valuesArgument;
/*
...
*/
@Test
public void test() {
/*
...
*/
// verify the number of calls
verify(myMockOfB, times(2)).dependencyMehtod(valuesArgument.capture());
// first call
assertEquals(3, valuesArgument.getAllValues().get(0).size());
// second call
assertEquals(1, valuesArgument.getAllValues().get(1).size());
}
Upvotes: 1