Unit Testing Mockito

Unit Testing Mockito

This tutorial assumes that you have some experience working with JUnit to perform unit testing of java classes. Mockito is an open source test framework which allows to create mock objects (Test double) to perform unit test in TDD (Test Driven Development or BDD(Behavior Driven Development).

In object oriented programming performing unit testing is difficult where class are dependent on many classes. For this reason, developer creates mock object that is simulation of actual objects whose behavior is same as real objects. Mockito framework allows you to create mock objects at the runtime using java proxy mechanism. You might have heard of below popular framework:

Out of all above I found Mockito easy to use to perform unit testing. It supports creating of mock object in various ways:

  • static mock method call: Below is sample how we use mock method and detail class you will see in the bottom:
private IMockitoMessage iMockitoMessage;

	@Before
	public void setUp() throws Exception {
		iMockitoMessage = mock(IMockitoMessage.class);
	}
	@After
	public void tearoff() {
		iMockitoMessage = null;
	}
  • Using annotation @mock: If you use annotation then you could initialize mock object either annotate class with @RunWith(MockitoJUnitRunner.class) or using MockitoAnnotations.initMocks(this) as below:

Unit Testing Mockito

To keep you aware: It has certain limitation where test can not be perform:

  • anonymous classes
  • primitive types
  • final classes

To understand better I will create sample maven project name: UnitTestingWithMockito with domain object, interface its implementation, class which call interface and consume its method. To perform unit test create two test classes which use different ways to create mock object. Below is final project structure:

Unit Testing Mockito

  •  Dependencies in pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javahonk</groupId>
	<artifactId>UnitTestingWithMockito</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>UnitTestingWithMockito</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.9.5</version>
		</dependency>
	</dependencies>
</project>
  • Domain object Message.java:
package com.javahonk.model;

public class Message {
	
	private String greeting;
	private String timeFrame;
	public String getGreeting() {
		return greeting;
	}
	public void setGreeting(String greeting) {
		this.greeting = greeting;
	}
	public String getTimeFrame() {
		return timeFrame;
	}
	public void setTimeFrame(String timeFrame) {
		this.timeFrame = timeFrame;
	}
	
	

}
  •  Create interface IMockitoMessage.java with one sample method:
package com.javahonk;

import com.javahonk.model.Message;

public interface IMockitoMessage {
	
	public Message timeFrame(String timeFrame);

}
  • MockitoMessageImpl.java which implements IMockitoMessage:
package com.javahonk;

import com.javahonk.model.Message;

public class MockitoMessageImpl implements IMockitoMessage{
	
	public Message timeFrame(String timeFrame) {
		
		Message message = new Message();
		
		if (timeFrame.equals("Morning")) {
			message.setGreeting("Good Morning");
			message.setTimeFrame("Morning");
			return message;
		}else if (timeFrame.equals("Afternoon")) {
			message.setGreeting("Good Afternoon");
			message.setTimeFrame("Afternoon");
			return message;			
		}else {
			message.setGreeting("Good Night");
			message.setTimeFrame("Evening");
			return message;			
		}		
	}

}
  • Client which use IMockitoMessage interface and call its method to get data:
package com.javahonk;

import com.javahonk.model.Message;

public class MockitoMessageImpleClient {

	public Message getGreetings(String timeFrame ){
		
		IMockitoMessage mockitoMessageImpl = new MockitoMessageImpl();
		return mockitoMessageImpl.timeFrame(timeFrame);		
		
	}
}
  • Test class 1: MockitoMessageImpleClientTest.java where you can use either @RunWith(MockitoJUnitRunner.class) annotation or MockitoAnnotations.initMocks(this) to create mock object to perform unit test:
package com.javahonk;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.javahonk.model.Message;


//@RunWith(MockitoJUnitRunner.class)
public class MockitoMessageImpleClientTest {

	@Mock
	private IMockitoMessage iMockitoMessage;

	@Before
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void testGetGreetings() {

		Message morning = new Message();
		morning.setGreeting("Good Morning");

		Message evening = new Message();
		evening.setGreeting("Good Evening");

		when(iMockitoMessage.timeFrame("Morning")).thenReturn(morning);
		when(iMockitoMessage.timeFrame("Evening")).thenReturn(evening);

		Assert.assertEquals("Good Morning",iMockitoMessage.timeFrame("Morning").getGreeting());
		Assert.assertEquals("Good Evening",iMockitoMessage.timeFrame("Evening").getGreeting());

		//Now we could verify if stubbed invocation happened or not
		verify(iMockitoMessage).timeFrame("Morning");		

	}

}
  •  Test Class 2: MockitoMessageImpleTestUsingMockMethod.java where mock method has been used to create mock object and executed unit test:
package com.javahonk;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.javahonk.model.Message;


public class MockitoMessageImpleTestUsingMockMethod {

	private IMockitoMessage iMockitoMessage;

	@Before
	public void setUp() throws Exception {
		iMockitoMessage = mock(IMockitoMessage.class);
	}
	@After
	public void tearoff() {
		iMockitoMessage = null;
	}

	@Test
	public void testGetGreetings() {

		Message morning = new Message();
		morning.setGreeting("Good Morning");

		Message evening = new Message();
		evening.setGreeting("Good Evening");

		when(iMockitoMessage.timeFrame("Morning")).thenReturn(morning);
		when(iMockitoMessage.timeFrame("Evening")).thenReturn(evening);

		Assert.assertEquals("Good Morning",iMockitoMessage.timeFrame("Morning").getGreeting());
		Assert.assertEquals("Good Evening",iMockitoMessage.timeFrame("Evening").getGreeting());

		//Now we could verify if stubbed invocation happened or not
		verify(iMockitoMessage).timeFrame("Morning");		

	}

}
  • To run unit test right click any of above two test class –> Run As –> JUnit Test:

Unit Testing Mockito

  • You will see below successful test result:

Unit Testing Mockito

  • For more details please refer Mockito documentation on its official site here 

download  Download project: UnitTestingWithMockito

Leave a Reply

Your email address will not be published. Required fields are marked *