Verifying the order of multiple instances method invocation

This post explains how to verify the order in which multiple instances are called. For example lets consider the below class

Class2


package package5;

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

Class3


package package5;

public class Class3 {
    public void method1() {
        System.out.println("Class3 method1");
    }
}

Class4


package package5;

public class Class4 {
    public void method1() {
        System.out.println("Class4 method1");
    }
}

All the above mentioned class methods are called by Class1 as shown below

Class1


package package5;

public class Class1 {
    private Class2 class2;
    private Class3 class3;
    private Class4 class4;
    
    public void method1() {
        class2.method1();
        class3.method1();
        class4.method1();
    }
}

To verify the order in which objects of all the three classes (ie., Class2, Class3, and Class4) are used. We use an instance of InOrder class which will contain the objects to be verified. We use Mockito’s static inOrder method to create an instance of InOrder class as shown below. We pass the objects as a paramter

InOrder inOrder = Mockito.inOrder(class2, class4, class3);

Now we mention the order by using the InOrder’s verify method as shown below
inOrder.verify(class2).method1();
inOrder.verify(class3).method1();
inOrder.verify(class4).method1();

Below is the complete code

Class1Test


package package5;

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;
    
    @Mock
    private Class3 class3;
    
    @Mock
    private Class4 class4;
    
    @Test
    public void testMethod1() {
        class1.method1();
        InOrder inOrder = Mockito.inOrder(class2, class4, class3);
        inOrder.verify(class2).method1();
        inOrder.verify(class3).method1();
        inOrder.verify(class4).method1();
    }
}

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