問題描述
要檢查與方法調用中的參數屬于某種類型的模擬的交互次數,可以這樣做
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);
}
};
}
匹配器通常會導致更易讀的測試和更有用的測試失敗消息.它們也往往是非??芍赜玫模鷷l現自己建立了一個為測試您的項目量身定制的庫.最后,您還可以使用 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模板網!