Verifying the order of multiple method invocations in a single instance

When multiple methods of single instance are invoked in an order in a class. We can verify the order of those method invocations using Mockito’s InOrder functionality. Consider the below code

Class2


package package4;

public class Class2 {
    public void method1() {
        System.out.println("Class2 method1");
    }
    
    public void method2() {
        System.out.println("Class2 method2");
    }
    
    public void method3() {
        System.out.println("Class2 method3");
    }
}

Class1


package package4;

public class Class1 {
    private Class2 class2;
    
    public void method1() {
        class2.method1();
        class2.method2();
        class2.method3();
    }
}

In the above code Class1’s method1, we are calling all the three methods of Class2. We can verify this order by creating an instance of InOrder class using Mockito’s static method inOrder as shown below
InOrder inOrder = Mockito.inOrder(class2);

Now we can verify the order using Mockito’s verify method as shown below
inOrder.verify(class2).method1();
inOrder.verify(class2).method2();
inOrder.verify(class2).method3();

Below is the complete code for your reference

Class1Test


package package4;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class Class1Test {
    @InjectMocks
    private Class1 class1;
    
    @Mock
    private Class2 class2;
    
    @Test
    public void testMethod1() {
        class1.method1();
        InOrder inOrder = Mockito.inOrder(class2);
        inOrder.verify(class2).method1();
        inOrder.verify(class2).method2();
        inOrder.verify(class2).method3();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s