279

Is there a way to verify if a methodOne is called before methodTwo in Mockito?

public class ServiceClassA {
    public void methodOne(){}
 }

public class ServiceClassB {
    public void methodTwo(){}
 }

public class TestClass {
    public void method(){
        ServiceClassA serviceA = new ServiceClassA();
        ServiceClassB serviceB = new ServiceClassB();
        serviceA.methodOne();
        serviceB.methodTwo();
    }
}
J. Katzwinkel
  • 1,923
  • 16
  • 22
froi
  • 7,268
  • 5
  • 40
  • 78

6 Answers6

420

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();
Dennis C
  • 24,511
  • 12
  • 71
  • 99
Koitoer
  • 18,778
  • 7
  • 63
  • 86
  • 11
    This is correct, though the calls to doNothing are not needed here except as a placeholder for other stubbing. Mockito will silently accept void method calls by default. – Jeff Bowman Feb 20 '14 at 10:34
  • 3
    It accept them while the object have no dependencies if the object have dependencies there will be an exception =) – Koitoer Feb 20 '14 at 17:12
  • 29
    consider `inOrder.verifyNoMoreInteractions();` after the last verify in this example to verify that no other calls were made. – DwB Jun 30 '16 at 19:02
  • 3
    Just to clarify: It is safe to define inOrder just before verify - after invoking some (tested) methods on mocks. – user3078523 Aug 16 '17 at 16:33
  • 1
    Are the results the same for `inOrder(firstMock, secondMock)` and `inOrder(secondMock, firstMock)`? Perhaps you can update the answer to make a note about this. – kevinarpe Dec 27 '17 at 10:49
  • You can also use the same mock in multiple calls of `inOrder.verify(...)` with different methods inside that mock. – Albert Hendriks Mar 20 '23 at 09:11
141

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}
}

public class Bar {
  public void firstThenSecond(Foo foo) {
    foo.first();
    foo.second();
  }
}

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  @Test
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);
    bar.firstThenSecond(mockFoo);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS
    orderVerifier.verify(mockFoo).first();
    orderVerifier.verify(mockFoo).second();

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();
  }
}
entpnerd
  • 10,049
  • 8
  • 47
  • 68
  • 2
    This should have been a comment on the accepted answer, not a whole new answer. – ach Nov 14 '16 at 19:12
  • 30
    I disagree with your comment @ach The code sample helps, so a new answer makes sense. – Snekse Apr 14 '17 at 16:49
  • 4
    Is there a way to verify the same method is called twice, but the verify the order of the parameters passed in? e.g. First `find('foo')`, then `find('bar')` – Snekse Apr 14 '17 at 16:51
  • 1
    Looks like this might be my answer http://stackoverflow.com/questions/36573399/how-to-verify-invocations-of-the-same-mock-method-with-the-same-argument-that-ch – Snekse Apr 14 '17 at 17:03
  • 1
    @Snekse Actually, you don't need to capture the arguments at all. Capturing is usually done to verify attributes of an object passed to a method when you don't know what that argument will be. For your case, you do know the values being passed, namely `"foo"` and `"bar"`. So you just need to add those arguments to your method call after you call `verify()`. So for your case, the code for the answer above would have the test code changed to have a line like the following: `firstThenSecondVerifier.verify(mockFoo).find("foo")`. I just verified that that code works for Mockito in an offline test. – entpnerd Apr 21 '17 at 20:19
  • @entpnerd, it worth to mention that `find("foo")` right after `find("foo")` should be checked mode `times(2)`. But `find("foo")`, `insert("foo")`, `find("foo")` can be checked in 3 lines with single-invocation verification mode in their order. – ony Jul 06 '17 at 14:53
  • @ony thanks for your contribution. I think that I did a poor job of conveying the intention of this answer. I'm trying to convey how to test the order of method calls, without regard to duplicate calls. I think that discussing duplicate calls of `first()` mildly detracts from the answer's intention. As per your comment, I have added more prose to better explain the intention of the answer. That being said, I really like your idea of discussing duplicate method calls, but I think that that discussion is best left for a separate answer, which I would be happy to upvote. :-) – entpnerd Jul 07 '17 at 02:32
  • 8
    This is actually a better example than the accepted answer because it shows a more typical usage than `doNothing()` – Archimedes Trajano May 01 '19 at 15:06
  • Thanks for the compliment @ArchimedesTrajano. – entpnerd May 01 '19 at 22:55
43

Yes, this is described in the documentation. You have to use the InOrder class.

Example (assuming two mocks already created):

InOrder inOrder = inOrder(serviceAMock, serviceBMock);

inOrder.verify(serviceAMock).methodOne();
inOrder.verify(serviceBMock).methodTwo();
Sean Connolly
  • 5,692
  • 7
  • 37
  • 74
LaurentG
  • 11,128
  • 9
  • 51
  • 66
7

For Kotlin users, you can go this way:

class MyTrackerTest {
    private val trackEventUseCase: TrackEventUseCase = mock()
    private val sut = MyTracker(trackEventUseCase)

    @Test
    fun `trackSomething SHOULD invoke tracker use case twice with correct event names WHEN called`() {
        sut.trackSomething()

        trackEventUseCase.inOrder {
            verify().invoke("Is it August?")
            verify().invoke("No!")
        }
    }

}

user3193413
  • 575
  • 7
  • 10
2

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}
Thracian
  • 43,021
  • 16
  • 133
  • 222
0

When verifying the invocation order of a single method call with different arguments it's essentially the same:

ServiceClass myMock = mock(ServiceClassA.class);

InOrder inOrder = inOrder(myMock);

inOrder.when(myMock).myMethod(42);
inOrder.when(myMock).myMethod(69);
Valerij Dobler
  • 1,848
  • 15
  • 25