junit

JUnit Mockito When thenReturn Example

In this example we will show you the usage of JUnit Mockito When thenReturn method. JUnit has many capabilities for testing the unit test cases for Java. But sometimes it lacks some of the common functionalities. Where it lacks and how we can complete, we will be showing in this example.

First of all, we have to be aware of the testing framework we are using here. We are using 2 test frameworks who works jointly to make a complete test scenario. First is JUnit and second is Mockito. They are independent of each other and works independently very well. But we are using here to show how we can leverage the use of both.

1. Introduction

If you are regular reader of my blogs about JUnit, then you are already aware of the JUnit. If not, you can see JUnit Hello World example. In JUnit, it is very cumbersome to test the scenarios where there is a dependency between the classes.

 
To rescue this, Mockito comes in picture. It is well known testing framework. In Mockito we mock the objects of the class and then do operations on them. Mockito makes heavy use of static methods. It is good to use static imports to make code shorter and more readable. IDE can be used to automatize adding static imports.

Tip
The when(...).thenReturn(...) method chain is be used to specify a condition and a return value for this condition.

2. Technologies Used

  • Java – language used for coding
  • Maven – dependency management tool
  • JUnit 4.12
  • Mockito 2.7.12
  • Eclipse – IDE for write code

3. Project Setup

Tip
You may skip project creation and jump directly to the beginning of the example below.

Create a new Maven project. Open Eclipse. Click File -> New -> Maven Project. Following screen will appear. Fill in the details and click on Next.

JUnit Mockito When thenReturn setup 1
Figure 1: JUnit Mockito When thenReturn setup 1

On next screen you will be prompted to enter some fields. Fill in the details as shown below.

JUnit Mockito When thenReturn setup 2
Figure 2: JUnit Mockito When thenReturn setup 2

With the clicking on Finish button, we are done with the setup of the project.

Lets start with an example now.

4. JUnit Mockito When thenReturn Example

We will be testing the DAO i.e. Data Access Objects layer. Since we do not have database, we can test the scenarios with the mocking of the class.

pom.xml
Add the following lines to pom.xml.

<dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.7.12</version>
        </dependency>

</dependencies>

4.1 Classes

Start by creating a Model class Employee.

Employee.java

package junitmockitowhenthenreturn;

/**
 * Model class of Employee
 * 
 * @author VINOD KUMAR KASHYAP
 *
 */
public class Employee {

	private Long employeeId;
	private String employeeName;
	private String bloodGroup;
	private String gender;
	private int awards;

	// parameterized constructor for creating objects
	public Employee(Long employeeId, String employeeName, String bloodGroup, String gender, int awards) {
		this.employeeId = employeeId;
		this.employeeName = employeeName;
		this.bloodGroup = bloodGroup;
		this.gender = gender;
		this.awards = awards;
	}

	public Long getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(Long employeeId) {
		this.employeeId = employeeId;
	}

	public String getEmployeeName() {
		return employeeName;
	}

	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public String getBloodGroup() {
		return bloodGroup;
	}

	public void setBloodGroup(String bloodGroup) {
		this.bloodGroup = bloodGroup;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public int getAwards() {
		return awards;
	}

	public void setAwards(int awards) {
		this.awards = awards;
	}

}

This is very simple model class of an Employee with getters and setters. Next, we will create a DAO class, that we will be used as a mock for testing. We have created a Singleton class. What is singleton class and why it is used? To know the answer you can visit Singleton Example.

EmployeeDAO.java

package junitmockitowhenthenreturn;

import java.util.Collections;
import java.util.List;

/**
 * Data Access Object for Employee Class. For simplicity we are making this
 * class Singleton
 * 
 * @author VINOD KUMAR KASHYAP
 *
 */
public class EmployeeDAO {

	// creating an object
	private static EmployeeDAO employeeDAO = new EmployeeDAO();

	/*
	 * private constructor. No objects of this class be created with new
	 * EmployeeDAO(). Use getInstance() instead
	 */
	private EmployeeDAO() {
	}

	// static method to create object
	public static EmployeeDAO getInstance() {
		return employeeDAO;
	}

	// add employee
	public Employee getEmployee(Long employeeId) {
		return null;
	}

	// list all employees
	public List getAll() {
		return Collections.emptyList();
	}

	// add employee
	public String addEmployee(Employee employee) {
		return employee.getEmployeeName();
	}

	// update employee
	public String updateEmployee(Employee employee) {
		return employee.getEmployeeName();
	}

	// delete employee
	public String deleteEmployee(Long employeeId) {
		return null;
	}

	// get all awards
	public int getAwards(Long employeeId) {
		return 0;
	}
}

4.2 Test Class

Now, we will create the main class that will be used to test all the cases.

Tip
Mockito, by default, compares arguments using equals () methods.

To get annotations to function, you need to either call MockitoAnnotations.initMocks( testClass ) (usually in a @Before method ) or use MockitoJUnit4Runner as a JUnit runner. In this example we will be using @RunWith(MockitoJUnitRunner.class).

EmployeeTest.java

package junitmockitowhenthenreturn;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class EmployeeTest {

	private static EmployeeDAO mockEmployeeDAO;
	private static Employee emp1;
	private static Employee emp2;

	@BeforeClass
	public static void init() {

		// set EmployeeDAO mock object
		mockEmployeeDAO = mock(EmployeeDAO.class);

		// create an Employee object
		emp1 = new Employee(1001L, "Vinod Kumar Kashyap", "A+", "Male", 2);

		// create another Employee object
		emp2 = new Employee(1002L, "Dhwani Kashyap", "A+", "Female", 5);

		// stubbing is done for test cases
		when(mockEmployeeDAO.getAll()).thenReturn(Arrays.asList(emp1, emp2));
		when(mockEmployeeDAO.getEmployee(1001L)).thenReturn(emp1);
		when(mockEmployeeDAO.addEmployee(emp2)).thenReturn(emp2.getEmployeeName());
		when(mockEmployeeDAO.updateEmployee(emp2)).thenReturn(emp2.getEmployeeName());

		// we are calling twice and see that always second call wins
		when(mockEmployeeDAO.deleteEmployee(1001L)).thenReturn("DELETED");
		when(mockEmployeeDAO.deleteEmployee(1001L)).thenReturn("REMOVED");

		/*
		 * when chaining is to be done. We can also use:
		 * when(mockEmployeeDAO.getAwards(1001L)).thenReturn(2,4,9);
		 */
		when(mockEmployeeDAO.getAwards(1001L)).thenReturn(2).thenReturn(4).thenReturn(9);

	}

	@Test
	public void getAllTest() {
		List allEmployees = mockEmployeeDAO.getAll();

		assertNotNull(allEmployees);
		assertEquals(2, allEmployees.size());
	}

	@Test
	public void getEmployeeTest() {
		Long employeeId = 1001L;
		Employee employee = mockEmployeeDAO.getEmployee(employeeId);

		assertNotNull(employee);
		assertEquals(Long.valueOf("1001"), employee.getEmployeeId());
		assertEquals("Vinod Kumar Kashyap", employee.getEmployeeName());
		assertEquals("A+", employee.getBloodGroup());
		assertEquals("Male", employee.getGender());
	}

	@Test
	public void addEmployeeTest() {
		String employeeName = mockEmployeeDAO.addEmployee(emp2);

		assertNotNull(employeeName);
		assertEquals("Dhwani Kashyap", employeeName);
	}

	@Test
	public void updateEmployeeTest() {
		String employeeName = mockEmployeeDAO.updateEmployee(emp2);

		assertNotNull(employeeName);
		assertEquals("Dhwani Kashyap", employeeName);
	}

	@Test
	public void deleteEmployeeTest() {
		String status = mockEmployeeDAO.deleteEmployee(1001L);

		assertEquals("REMOVED", status);
	}

	@Test
	public void multipleCallsTest() {
		int awards = mockEmployeeDAO.getAwards(1001L);
		System.out.println(awards);

		awards = mockEmployeeDAO.getAwards(1001L);
		System.out.println(awards);

		awards = mockEmployeeDAO.getAwards(1001L);
		System.out.println(awards);
	}
}

Examining the class.
Line 16: We are using @RunWith(MockitoJUnitRunner.class), so that our program will run with Mockito.
Line 23: @BeforeClass annotation of JUnit is used for initial setup. This will run before running any other test case.
Line 27: EmployeeDAO mock is being created at this line.
Line 30, 33: New Employee objects are being created
Line 36-39: stubbing is done so that when some condition is matched what needs to be done i.e. we are using the When with thenReturn of the Mockito framework. This is the main crux of the example. This is where we have used our core principal of our example.
Line 42,43: multiple calls to same method. We will see the side effects below.
Line 49: Chaining of stubs.

To run this example, right click on project in eclipse, Run As -> Maven test.

4.2.1 Output

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running junitmockitowhenthenreturn.EmployeeTest
2
4
9
Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.577 sec

Results :

Tests run: 6, Failures: 0, Errors: 0, Skipped: 0

Or, if you run the EmployeeTest.java by right clicking on class and then Run As -> JUnit Test, you will following output.

JUnit Mockito When thenReturn output
Figure 3: JUnit Mockito When thenReturn output

All our test cases have passed.

5. Other use cases of When thenReturn

Let’s see some more ways in which we can use the when(...).thenReturn(...) method.

Tip
Once stubbed, the method will always return a stubbed value, regardless of how many times it is called. Last stubbing is more important – when you stubbed the same method with the same arguments many times.

For example:
In our class EmployeeTest.java at line no 43 (when(mockEmployeeDAO.deleteEmployee(1001L)).thenReturn("REMOVED");). If you call this 10 times it will always return same value.
But if we want to return different values, then we can chain the stubs. See the example below.

when(mockEmployeeDAO.getAwards(1001L)).thenReturn(2).thenReturn(4).thenReturn(9);

or we can simply use

when(mockEmployeeDAO.getAwards(1001L)).thenReturn(2,4,9);

Here is the code.

	@Test
	public void multipleCallsTest() {
		int awards = mockEmployeeDAO.getAwards(1001L);
		System.out.println(awards);

		awards = mockEmployeeDAO.getAwards(1001L);
		System.out.println(awards);

		awards = mockEmployeeDAO.getAwards(1001L);
		System.out.println(awards);
	}

Running this code will print the following output:

2
4
9

Furthermore, if we call same methods with different return values then always the last call wins. For example, all mockEmployeeDAO.deleteEmployee(1001L) calls will return “REMOVED”

when(mockEmployeeDAO.deleteEmployee(1001L)).thenReturn("DELETED");
when(mockEmployeeDAO.deleteEmployee(1001L)).thenReturn("REMOVED");

Here is the code:

	@Test
	public void deleteEmployeeTest() {
		String status = mockEmployeeDAO.deleteEmployee(1001L);

		assertEquals("REMOVED", status);
	}

Running above test will always return “REMOVED”.

6. Conclusion

JUnit Mockito When thenReturn example explains the usage of the special method of Mockito framework. This example explains the usage of the when(...).thenReturn(...) method and the scenarios in which it is used.

7. Download the Eclipse project

This is an example of JUnit Mockito When thenReturn.

Download
You can download the full source code of this example here: JUnitMockitoWhenthenReturn.zip

Vinod Kumar Kashyap

Vinod is Sun Certified and love to work in Java and related technologies. Having more than 13 years of experience, he had developed software's including technologies like Java, Hibernate, Struts, Spring, HTML 5, jQuery, CSS, Web Services, MongoDB, AngularJS, AWS. He is also a JUG Leader of Chandigarh Java User Group.
Subscribe
Notify of
guest

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

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Larry
Larry
4 years ago

Completely useless. Please explain what is “When thenReturn” then give example.

Michael
Michael
4 years ago
Reply to  Larry

You dont have to read it anymore. For me the article was very helpful.

Back to top button