Mockito:如何validation一个方法只被调用一次,确切的参数忽略了对其他方法的调用?

在Java中使用Mockito如何validation方法只调用一次精确参数忽略对其他方法的调用?

示例代码:

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 (ie the call to clear()) } } 

TODO: don't allow all other invocations with add()应该做什么TODO: don't allow all other invocations with add()部分TODO: don't allow all other invocations with add()

尝试失败:

  1. verifyNoMoreInteractions(foo);

不。 它不允许调用其他方法,如clear()

  1. verify(foo, times(0)).add(any());

不。 它没有考虑我们允许一个调用add("1")

 Mockito.verify(foo, Mockito.times(1)).add("1"); Mockito.verify(foo, Mockito.times(1)).add(Mockito.anyString()); 

第一次verify检查预期的参数化调用,第二次verify检查是否只有一个要add调用。

之前的答案可以进一步简化。

 Mockito.verify(foo).add("1"); Mockito.verify(foo).add(Mockito.anyString()); 

单参数verify方法只是times(1)实现的别名。