要检查与方法调用中的参数属于某种类型的模拟的交互次数,可以这样做
To check the number of interactions with a mock where the parameter in the method call is of a certain type, one can do
mock.someMethod(new FirstClass());
mock.someMethod(new OtherClass());
verify(mock, times(1)).someMethod(isA(FirstClass.class));
这要归功于对 isA
的调用,因为 someMethod
被调用了两次,但只有一次使用参数 FirstClass
This will pass thanks to the call to isA
since someMethod
was called twice but only once with argument FirstClass
然而,当使用 ArgumentCaptor 时,这种模式似乎是不可能的,即使 Captor 是为特定参数 FirstClass
However, this pattern seems to not be possible when using an ArgumentCaptor, even if the Captor was created for the particular argument FirstClass
这不起作用
mock.someMethod(new FirstClass());
mock.someMethod(new OtherClass());
ArgumentCaptor<FirstClass> captor = ArgumentCaptor.forClass(FirstClass.class);
verify(mock, times(1)).someMethod(captor.capture());
它说模拟被多次调用.
在捕获参数以供进一步检查时,有什么方法可以完成此验证?
Is there any way to accomplish this verification while capturing the argument for further checking?
我建议使用 Mockito 的 Hamcrest 集成为其编写一个好的、干净的匹配器.这允许您将验证与传递参数的详细检查结合起来:
I recommend using Mockito's Hamcrest integration to write a good, clean matcher for it. That allows you to combine the verification with detailed checking of the passed argument:
verify(mock, times(1)).someMethod(argThat(personNamed("Bob")));
Matcher<Person> personNamed(final String name) {
return new TypeSafeMatcher<Person>() {
public boolean matchesSafely(Person item) {
return name.equals(item.getName());
}
public void describeTo(Description description) {
description.appendText("a Person named " + name);
}
};
}
匹配器通常会导致更易读的测试和更有用的测试失败消息.它们也往往是非常可重用的,您会发现自己建立了一个为测试您的项目量身定制的库.最后,您还可以使用 JUnit 的 Assert.assertThat()
将它们用于正常的测试断言,因此您可以双重使用它们.
Matchers generally lead to more readable tests and more useful test failure messages. They also tend to be very reusable, and you'll find yourself building up a library of them tailored for testing your project. Finally, you can also use them for normal test assertions using JUnit's Assert.assertThat()
, so you get double use out of them.
这篇关于mockito 验证与 ArgumentCaptor 的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!