Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying two invocations of the same method with another method invocation in between, when order is important, in Mockito

Tags:

java

mockito

I thought this would work:

InOrder inOrder = new InOrder(mock);
inOrder.verify(mock).method1();
inOrder.verify(mock).method2();
inOrder.verify(mock).method1();

… but Mockito says undesired invocation of mock.method1(). Wanted 1 time, but was 2 times. I changed my code to this:

inOrder.verify(times(2), mock).method1();
inOrder.verify(mock).method2();

It should work, but now I do not test what I wanted to test in the first place. Could someone please point out what I am doing wrong, or if Mockito is too limited for these kind of test?

like image 677
Fredrik Israelsson Avatar asked Jan 10 '14 10:01

Fredrik Israelsson


People also ask

What does verify method do in Mockito?

Mockito Verify methods are used to check that certain behavior happened. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called.

Which method in Mockito verifies that no interaction has happened with a mock in Java?

Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.

What is verifyNoMoreInteractions?

public static void verifyNoMoreInteractions(Object... mocks) Checks if any of given mocks has any unverified interaction. We can use this method after calling verify() methods. It is to make sure that no interaction is left for verification.


1 Answers

It tested this with Mockito 1.9.5 and it works:

@Test
public void foo() {
    Runnable outer = Mockito.mock(Runnable.class, "outer");
    Runnable inner = Mockito.mock(Runnable.class, "inner");

    outer.run();
    inner.run();
    outer.run();

    InOrder order = Mockito.inOrder(outer, inner);
    order.verify(outer).run();
    order.verify(inner).run();
    order.verify(outer).run();
}

So if you aren't doing anything else wrong your code should work. What Mockito version are you using?

like image 79
SpaceTrucker Avatar answered Sep 20 '22 17:09

SpaceTrucker