問題描述
在 Java 中使用 Mockito 如何驗證一個方法只被調(diào)用了一次,而忽略了對其他方法的調(diào)用?
Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?
示例代碼:
public class MockitoTest {
interface Foo {
void add(String str);
void clear();
}
@Test
public void testAddWasCalledOnceWith1IgnoringAllOtherInvocations() throws Exception {
// given
Foo foo = Mockito.mock(Foo.class);
// when
foo.add("1"); // call to verify
foo.add("2"); // !!! don't allow any other calls to add()
foo.clear(); // calls to other methods should be ignored
// then
Mockito.verify(foo, Mockito.times(1)).add("1");
// TODO: don't allow all other invocations with add()
// but ignore all other calls (i.e. the call to clear())
}
}
TODO: 不允許使用 add()
部分的所有其他調(diào)用中應該做什么?
What should be done in the TODO: don't allow all other invocations with add()
section?
已經(jīng)嘗試失敗:
verifyNoMoreInteractions(foo);
不.它不允許調(diào)用其他方法,例如 clear()
.
Nope. It does not allow calls to other methods like clear()
.
verify(foo, times(0)).add(any());
不.它沒有考慮到我們允許一次調(diào)用 add("1")
.
Nope. It does not take into account that we allow one call to add("1")
.
推薦答案
Mockito.verify(foo, Mockito.times(1)).add("1");
Mockito.verify(foo, Mockito.times(1)).add(Mockito.anyString());
第一個 verify
檢查預期的參數(shù)化調(diào)用,第二個 verify
檢查是否只有一次對 add
的調(diào)用.
The first verify
checks the expected parametrized call and the second verify
checks that there was only one call to add
at all.
這篇關于Mockito:如何驗證一個方法只被調(diào)用一次,使用精確的參數(shù)忽略對其他方法的調(diào)用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!