In this post under Mockito, I will show with example how to stub a non-static void method to do nothing.
For our example, I will use the below class
MyCustomLogger
package package9;public class MyCustomLogger { public void info() { System.out.println("adding a and b"); }}
Calculator
package package9;public class Calculator { private MyCustomLogger myCustomLogger; public int add(int a, int b){ myCustomLogger.info(); return a + b; }}
As you can see in the above code, the “Calculator” class is depender and “MyCustomLogger” class is dependee.
We need to test the “add” method of “Calculator” class and so we have to mock “MyCustomLogger” class.
Currently the “MyCustomLogger” class is printing the message to console.
As part of this example, we will create a mock of “MyCustomLogger” and create a stub of its void method “info” to do nothing.
For this we will use “Mockito” class “doNothing” method.
Below is the complete test class for your reference.
CalculatorTest
package package9;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.Mockito;import org.mockito.invocation.InvocationOnMock;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.stubbing.Answer;import package8.Calculator;import package8.MyCustomLogger;import static org.mockito.ArgumentMatchers.anyString;@ExtendWith(MockitoExtension.class)public class CalculatorTest { @InjectMocks private Calculator calculator; @Mock private MyCustomLogger myCustomLogger; @Test public void testAdd() { Mockito.doNothing().when(myCustomLogger).info(); calculator.add(10, 5); }}
In the above code, at line 24, I am using “doNothing” method to stub “info” method of “MyCustomLogger” class to do nothing.
In this way we can stub a non-static void method to do nothing.