Mockito:如何验证一个方法只调用一次精确参数忽略对其他方法的调用?

Igo*_*hin 30 java testing unit-testing mocking mockito

在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())
    }

}
Run Code Online (Sandbox Code Playgroud)

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

尝试失败:

  1. verifyNoMoreInteractions(foo);

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

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

不.它没有考虑到我们允许一个电话add("1").

hun*_*ter 54

Mockito.verify(foo, Mockito.times(1)).add("1");
Mockito.verify(foo, Mockito.times(1)).add(Mockito.anyString());
Run Code Online (Sandbox Code Playgroud)

第一个verify检查预期的参数化调用,第二个verify检查只有一个调用add.


小智 9

The previous answer can be simplified even further.

Mockito.verify(foo).add("1");
Mockito.verify(foo).add(Mockito.anyString());
Run Code Online (Sandbox Code Playgroud)

The single parameter verify method is just an alias to the times(1)implementation.

  • 如果您主要关注最小化字符数,则此简化确实可以提供价值。但是,被接受的Answer也具有价值,因为它在时间上更为明确:它使时间清楚了1倍,而此答案中的代码只能通过查看JavaDoc的#verify来表达这一点。对于不熟悉#validate默认值的编码人员而言,接受的答案将更加清楚,并且可能没有理由查看其Javadoc。 (5认同)