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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39452438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:10:09  来源:igfitidea点击:

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

javaunit-testingtestingmockingmockito

提问by Igor Mukhin

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()部分应该做什么?

Already unsuccessfully tried:

已经尝试不成功:

  1. verifyNoMoreInteractions(foo);
  1. verifyNoMoreInteractions(foo);

Nope. It does not allow calls to other methods like clear().

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

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

Nope. It does not take into account that we allow one call to add("1").

不。它没有考虑到我们允许对 进行一次调用add("1")

采纳答案by hunter

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

The first verifychecks the expected parametrized call and the second verifychecks that there was only one call to addat all.

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

回答by Travis Miller

The previous answer can be simplified even further.

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

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

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

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