Mockito is industry wide mocking framework for unit test. It gives an ability to a developer to write his/her code without depending on other developer’s code. Testing void method is hard because it doesn’t return any value. In this blog, I will show, how we can test our void method using Mockito.
Purpose
Unit testing void method of a class.
Dependency
org.mockito
mockito-all
1.10.19
Implementation
Class to hold void method:
package com.vsubedi.voidTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SomeVoidMethod {
private static final Logger logger = LoggerFactory.getLogger(SomeVoidMethod.class);
public void printLogs(){
logger.info("This method has been executed");
}
}
Testing above class’s void method:
package com.vsubedi.voidTest;
import static org.mockito.Mockito.verify;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestVoidMethod {
private static final Logger logger = LoggerFactory.getLogger(TestVoidMethod.class);
@InjectMocks
@Spy
private SomeVoidMethod someVoidMethod;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
logger.info("============ START UNIT TEST ==============");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
logger.info("============ END UNIT TEST ==============");
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testPrintLogs() {
someVoidMethod.printLogs();
//verifying the interaction to the method
verify(someVoidMethod).printLogs();
}
}
We need to have @Spy annotation to run verify() method which is supplied by Mockito. verify tells that printLogs() of SomeVoidMethod class has been executed at least once.
This is just a very simple example to show how we can test void method. Void methods can be complex. We can also test those complex void methods using Mockito.