我有一个类 A,它必须对其依赖项 B 的方法进行两次后续调用,该方法将集合作为参数:
class A{
private B myDependency;
public myClassMethod() {
// ... on more than one occasion calls myDependency.dependencyMehtod(someColleciton);
}
}
class B{
public void dependencyMehtod(Collection<Something> input)
}
我想为 A 类编写一个单元测试(最好使用 Mockito)来验证 依赖项方法被精确调用了给定的次数,并且还在每次后续调用时验证输入 Collection 的大小(参数的大小在调用之间有所不同)。 我该怎么做?
我尝试使用
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
但是,我从 Mockito 收到一条错误消息:在预期大小为 3 的集合的地方发现了大小为 1 的集合。我做错了什么?
最佳答案
您可以使用ArgumentCaptor
。这是一个例子:
@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());
}
关于java - 验证 Mockito 中同一方法的后续调用的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26618595/