問(wèn)題描述
在 Java 中使用 Mockito 如何驗(yàn)證一個(gè)方法只被調(diào)用了一次,而忽略了對(duì)其他方法的調(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)用中應(yīng)該做什么?
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());
不.它沒(méi)有考慮到我們?cè)试S一次調(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());
第一個(gè) verify
檢查預(yù)期的參數(shù)化調(diào)用,第二個(gè) verify
檢查是否只有一次對(duì) 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.
這篇關(guān)于Mockito:如何驗(yàn)證一個(gè)方法只被調(diào)用一次,使用精確的參數(shù)忽略對(duì)其他方法的調(diào)用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!