Thursday, June 2, 2016

Mocking void methods with Mockito in JUnit

Sources:

There are multiple ways to stub a void method with Mockito.
I chose to use doAnswer() because this way it will show up in the test coverage report (EclEmma in Eclipse) properly. When I used doThrow(), it did not appear as covered, because an exception was thrown.
As a brute-force approach, I used the System.out to verify that the method was called.
public class MyClassTest {
 private MyOtherClass mockMyOtherClass;
 private MyClass myClass;
 
 private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
 private final String successfulRunMessage = "Successful run";
 private Answer successfulRunAnswer = new Answer() {
  public Void answer(InvocationOnMock invocation) {
   System.out.println(successfulRunMessage);
   return null;
  }
 };

 @Before
 public void setUpStreams() {
  System.setOut(new PrintStream(outContent));
 }

 @After
 public void cleanUpStreams() {
  System.setOut(null);
 }

 @Before
 public void setUp() {
  mockMyOtherClass = Mockito.mock(MyOtherClass.class);
  myClass = new MyClass(mockMyOtherClass);
 }

 @Test
 public void testVoidMethodCall() {
  Mockito.doAnswer(successfulRunAnswer).when(mockMyOtherClass).myVoidMethod());
  myClass.runMyVoidMethod();
  assertEquals(successfulRunMessage, outContent.toString().trim());
 }
}