简体   繁体   English

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

[英]Mockito: How to verify a method was called only once with exact parameters ignoring calls to other methods?

Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?在 Java 中使用 Mockito 如何验证一个方法只被调用一次,并使用精确参数忽略对其他方法的调用?

Sample code:示例代码:

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

}

What should be done in the TODO: don't allow all other invocations with add() section?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()

Already unsuccessfully tried:已经尝试不成功:

  1. verifyNoMoreInteractions(foo);

Nope.不。 It does not allow calls to other methods like clear() .它不允许调用其他方法,如clear()

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

Nope.不。 It does not take into account that we allow one call to add("1") .它没有考虑到我们允许一次调用add("1")

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

The first verify checks the expected parametrized call and the second verify checks that there was only one call to add at all.第一个verify检查预期的参数化调用,第二个verify检查是否只有一个调用要add

The previous answer can be simplified even further.前面的答案可以进一步简化。

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

The single parameter verify method is just an alias to the times(1) implementation.单参数verify方法只是times(1)实现的别名。

对于在Junit 5/Jupiter使用Mockito和验证静态方法的任何人, Mockito一眼这个不错的方法https://stackoverflow.com/a/63242611/4809938

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM