Stubbing void methods to do nothing

This post explains how to change the implementation of void methods to do nothing for testing purposes.

Below is the example

Classes to be tested


package package13;

public class Class2 {
    public void method2(String value) {
        value = value + " World";
    }
}

package package13;

public class Class1 {
    private Class2 class2;
    
    public String method1(String value) {
        class2.method2(value);
        return value;
    }
}

Test Class


1  package package13;
2  
3  import static org.junit.Assert.assertEquals;
4  import static org.mockito.Matchers.*;
5  
6  import org.junit.Test;
7  import org.junit.runner.RunWith;
8  import org.mockito.InjectMocks;
9  import org.mockito.Mock;
10 import org.mockito.Mockito;
11 import org.mockito.runners.MockitoJUnitRunner;
12 
13 @RunWith(MockitoJUnitRunner.class)
14 public class Class1Test {
15  @InjectMocks
16  private Class1 class1;
17  
18  @Mock
19  private Class2 class2;
20  
21  @Test
22  public void testMethod1() {
23      Mockito.doNothing().when(class2).method2(anyString());
24              String value = class1.method1("Hello");
25      assertEquals("Hello", value);
26  }
27 }

Explanation

We want to test Class1’s method1. Class1’s method1 calls Class2’s method2. While testing we want to the Class2’s method2 to do nothing.

This can be achieved by creating a test stub of Class2 and make the method do nothing using the below code. Refer to line 23 in the Test Class.
Mockito.doNothing().when(class2).method2(anyString());

In the code snippet, we are telling Mockito that when Class2’s method2 is called with any string do nothing.

When the test class is ran, the return value of Class1’s method1 will be “Hello” instead of “Hello World”.

Leave a Reply