Mockito:如何验证一个方法只被调用了一次,参数精确,忽略了对其他方法的调用?
2022-08-31 13:58:52
在Java中使用Mockito如何验证一个方法只被调用一次,并且参数精确,忽略对其他方法的调用?
示例代码:
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: don't allow all other invocations with add()
已尝试失败:
verifyNoMoreInteractions(foo);
不。它不允许调用其他方法,如 。clear()
verify(foo, times(0)).add(any());
不。它没有考虑到我们允许一个调用到 。add("1")