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

JavaUnit TestingTestingMockingMockito

Java Problem Overview


Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?

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?

Already unsuccessfully tried:

  1. verifyNoMoreInteractions(foo);

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

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

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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

verify(mock.methodName()).called(1// or any number that u should check);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIgor MukhinView Question on Stackoverflow
Solution 1 - JavahunterView Answer on Stackoverflow
Solution 2 - JavaTravis MillerView Answer on Stackoverflow
Solution 3 - JavaReza TaghizadehView Answer on Stackoverflow