Verifying the exact number of method invocations

This post explains how to verify that a method is executed desired number of times using Mockito framework.

Below is the code of the class to be tested.

Class1 code


package package14;

import java.util.List;

public class Class1 {
    private List list;
    
    public void method1() {
        for(int i = 0; i < 10 ;i++) {
            list.add(i);
        }
    }
}

In the above code, we are calling add method of list instance 10 times.

To write a test case that will make sure that the add method is called 10 times we use Mockito’s two static methods
1) verify
2) times

Below is the code of the test class

Test Class


1  package package14;
2  
3  import java.util.List;
4  
5  import org.junit.Test;
6  import org.junit.runner.RunWith;
7  import org.mockito.InjectMocks;
8  import org.mockito.Mock;
9  import org.mockito.Mockito;
10 import org.mockito.junit.MockitoJUnitRunner;
11 
12 import static org.mockito.ArgumentMatchers.anyInt;
13 import static org.mockito.Mockito.times;
14 
15 @RunWith(MockitoJUnitRunner.class)
16 public class Class1Test {
17  @InjectMocks
18  private Class1 class1;
19  
20  @Mock
21  private List list;
22  
23  @Test
24  public void testMethod1() {
25      class1.method1();
26      Mockito.verify(list, times(10)).add(anyInt());
27  }
28 }

Refer to line 26, where we are telling the mockito framework to verify that list.add method is called 10 times.

Advertisements

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s