Mockito

JUnit Mockito Example

1. Introduction

Methods and ways to create Unit Test cases have evolve ever since it’s introduction. New tools and API´s are now available and they provide a more advanced scheme on creating and executing JUnit Test cases. Services have become more incubated, so creating integration test cases has been a daunting task for any developer.

The introduction of this new development approach made revolutionary changes in Unit testing as well and a lot of testing framework came and rise the level at the playing field. With this, the need to create mocking objects to mimic Java objects in their runtime has never been more important, especially on critical enterprise software.

In this post, I’ll be showing one of the most widely used and popular JUnit Testing Mocking framework – Mockito.

2. Mockito Framework

Mockito is one of the widely used testing API for Java. Tons of examples are accepted by the massive Java community. Back in 2008, Dan North said that this was the future model of testing java applications. The popularity of Mockito and the overall Java projects in Github that use this API, clearly state that the prediction was true.

3. Eclipse Example

Let’s take a deep dive into an example. In this example we’ll create the following:

  • Create a new Maven Project
  • Define the dependencies we need. That is JUnit and Mockito
  • Code some examples

3.1 Maven Project

Let’s first create a new Maven project. In your eclipse click on File > New Project > Maven Project. Tick on create a simple project fill up the group id, artefact id and hit Finish.

Figure 1.0 Maven project
Figure 1.0 Maven project

3.2 pom.xml configuration

We then include the dependencies we need. This will download the libraries for our project.

pom.xml

<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.jgc.areyes.junit</groupId>
	<artifactId>junit-mockito-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.9.5</version>
		</dependency>
	</dependencies>
</project>

3.3 Test Case Example

JUnitServiceTestExample.java

package com.areyes1.jgc.mockito.e;

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import java.util.Iterator;

import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;

/**
 * The Class JUnitServiceTestExample.
 */
public class JUnitServiceTestExample {

	/**
	 * Test1.
	 */
	@Test
	public void testSimpleInt() {
		// create mock
		TestService test = Mockito.mock(TestService.class);

		// define return value for method getUniqueId()
		when(test.getUniqueId()).thenReturn(43);

		// use mock in test....
		assertEquals(test.getUniqueId(), 43);
	}

	/**
	 * Test more than one return value.
	 */
	// Demonstrates the return of multiple values
	@Test
	public void testMoreThanOneReturnValue() {
		Iterator i = mock(Iterator.class);
		when(i.next()).thenReturn("Mockito").thenReturn("is neat!!");
		String result = i.next() + " " + i.next();
		assertEquals("Mockito is neat!!", result);
	}

	/**
	 * Test return value dependent on method parameter.
	 */
	@Test
	public void testReturnValueDependentOnMethodParameter() {
		Comparable c = mock(Comparable.class);
		when(c.compareTo("Mockito")).thenReturn(1);
		when(c.compareTo("Eclipse")).thenReturn(2);
		// assert
		assertEquals(1, c.compareTo("Mockito"));
	}

	/**
	 * Test return value in dependent on method parameter.
	 */
	@Test
	public void testReturnValueInDependentOnMethodParameter() {
		Comparable c = mock(Comparable.class);
		when(c.compareTo(anyInt())).thenReturn(-1);
		assertEquals(-1, c.compareTo(9));
	}

	@Test
	public void testVerify() {
		// create and configure mock
		TestService test = Mockito.mock(TestService.class);
		when(test.getUniqueId()).thenReturn(43);

		// call method testing on the mock with parameter 12
		test.testing(12);
		test.getUniqueId();
		test.getUniqueId();
		test.someMethod("Hello World");
		test.someMethod("called at least once");
		test.someMethod("called at least twice");
		test.someMethod("called five times");
		test.someMethod("called at most 3 times");

		// now check if method testing was called with the parameter 12
		verify(test).testing(Matchers.eq(12));

		// was the method called twice?
		verify(test, times(2)).getUniqueId();

		// other alternatives for verifiying the number of method calls for a
		// method
		verify(test, never()).someMethod("never called");
		verify(test, atLeastOnce()).someMethod("called at least once");
		
		//	Will all fail because we didn't met the conditions.
		verify(test, atLeast(2)).someMethod("called at least twice");	 
		verify(test, times(5)).someMethod("called five times");
		verify(test, atMost(3)).someMethod("called at most 3 times");
	}

}

The example above showcases the different unique usage of Mockito. Aside from just mocking objects, it also perfectly compliments what we call “behaviour driven” test cases. This means that the test case is aimed at testing the behaviour or any method calls within the services aside from the output itself.

Let’s go over each method:

  • testSimpleInt – the test case creates a mock class and calls the method. It enforces the method to use 43 as it’s return. This is then tested via an assertEquals method as shown.
  • testMoreThanOneReturnValue – the cases mocked an iterator class and sets a new value for the first record. The example shown concatenates two new strings on the 1st element. This record is then tested via an assertEquals method.
  • testReturnValueInDependentOnMethodParameter – The test case shows how we can dynamically use other results even in our comparison logic. In this example, we forced the comparisons to return values that are then tested via an assertEquals method.
  • testVerify – the test case showcases how we can test the behaviour of a method within the class. It tests how many calls were made to the method and if there are any changes to the return types. This is a powerful feature because not only allows developers to test results, but also the behaviour of a specific service can be tested.

Mockito has redefined the creation of test cases. Almost every project globally uses the API. It´s not just about mocking objects and classes but its also that it has created a venue for developers to develop more concrete, bulletproof test cases that ensure the stability of the software.

4 Output

Running the test case above will give the output below.

Figure 2.0 Mockito test cases output
Figure 2.0 Mockito test cases output

5. Download the Eclipse project

This was an example of JUnit Mockito.

Download
You can download the full source code of this example here: junit-mockito-example

Alvin Reyes

Alvin has an Information Technology Degree from Mapua Institute of Technology. During his studies, he was already heavily involved in a number of small to large projects where he primarily contributes by doing programming, analysis design. After graduating, he continued to do side projects on Mobile, Desktop and Web Applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button