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

}

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

已经尝试失败:

  1. verifyNoMoreInteractions(foo);

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

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

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

原文由 Igor Mukhin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答
Mockito.verify(foo, Mockito.times(1)).add("1");
Mockito.verify(foo, Mockito.times(1)).add(Mockito.anyString());

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

原文由 hunter 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

原文由 Travis Miller 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题