Testing Void Method Using Mockito

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:

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
</dependency>

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.

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s