
The Mockito Framework tutorial aims to teach basic and advanced Java-based mockito testing techniques for unit testing. Mockito is a well known open source framework for simulating objects in software testing. Mockito is a mocking framework which is used create test APIs that might be simple or complicated in order to unit test functionalities of application.
If you need testing, you may use the Mockito framework in addition to other well-known frameworks like JUnit and TestNG. Mockito enables worry-free creation of mock objects, or worry-free object cloning. You should also be aware that the Mockito framework uses Java reflection internally to construct objects of service.
In this tutorial we will learn unit test with mockito, we will write test cases in java application using mockito, how to run mockito junit test, how to view mockito junit test report with details.
Table of Contents
What is Mocking concept?
Mocking is a way to test the functionality of a class without the need for a database connection or properties files. The object is created using the mocking technique, which basically acts as a dummy or imitation of the genuine objects. Mock objects work with dummy data when some dummy data is passed.
Mocking techniques are not limited to Java only but we can use in any object-oriented programming language.
Before going deep into the Mockito framework, one must understand the three main concepts of mocking – Mock, Stub and Fake.
Stub
Stub objects are essentially dummy objects that contain data (really, a pre-configured response) and and which are returned when the test is performed.
Fake
Fake objects are those that have functioning implementations that are confined to the system being tested. It uses memory or a collection to store data.
Mock
Mock objects are objects of a certain kind that also serve as mock versions of actual things. We specify responses to mock objects for testing. Additionally, we test the system’s behavior using mock objects.
What are the benefits of Mockito Framework?
Mockito Framework has the following benefits in testing. Because of these benefits Mockito has become the most widely used framework for testing.
- No handwriting is required for Mockito code.
- Mockito provides returned values, which are significant from a validation perspective.
- To identify the cause of an exception, Mockito offers stack traces and exception validation.
- Most importantly, the annotations are supported. As a result, you won’t have to write as much or any XML code.
- Since runtime creation of mock objects. So you can safely rename and refactor the method names of interfaces without changing the test code.
- The execution of a method might sometimes be crucial. So method order execution is supported by Mockito as well.
Unit tests with Mockito Framework example program
Let’s start with test cases in a Java application using Mockito. We have developed a spring boot application (which is not mandatory you can use simple maven application). In this application we have a test class in which we have written some test cases.
In this example we have not used @RestController or @MockBean. This is a simple example to demonstrate unit testing. Based on this you can also create @RestController.
Department.java
package com.mockitodemo.model;
public class Department {
private String deptName;
public Department(String deptName) {
super();
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}
Employee.java
package com.mockitodemo.model;
public class Employee {
private String empName;
private double salary;
private Department department;
public Employee(String empName, double salary, Department department) {
super();
this.empName = empName;
this.salary = salary;
this.department = department;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
EmployeeService.java
package com.mockitodemo.service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.mockitodemo.model.Department;
import com.mockitodemo.model.Employee;
public class EmployeeService {
private static final String HR = "HR";
private static final String DEVELOPER = "Developer";
private static final String TESTER = "Tester";
List<Employee> employeeList;
public EmployeeService() {
employeeList = new ArrayList<>();
Department hrDepartment = new Department(HR);
Department developerDepartment = new Department(DEVELOPER);
Department testerDepartment = new Department(TESTER);
Employee employee = new Employee("SCOTT", 30000, hrDepartment);
employeeList.add(employee);
employee = new Employee("SMITH", 50000, developerDepartment);
employeeList.add(employee);
employee = new Employee("AKASH", 40000, developerDepartment);
employeeList.add(employee);
employee = new Employee("JANNY", 20000, testerDepartment);
employeeList.add(employee);
}
public List<Employee> getDeveloper() {
return employeeList.stream().filter(x -> x.getDepartment().getDeptName().equals(DEVELOPER))
.collect(Collectors.toList());
}
public List<Employee> getTester() {
return employeeList.stream().filter(x -> x.getDepartment().getDeptName().equals(TESTER))
.collect(Collectors.toList());
}
public List<Employee> getEmployee(String deptName) {
List<Employee> list = employeeList.stream().filter(x -> x.getDepartment().getDeptName().equals(deptName))
.collect(Collectors.toList());
if (list.size() > 0) {
return list;
}
throw new IllegalArgumentException("Not a valid department");
}
}
EmployeeController.java
package com.mockitodemo.controller;
import java.util.List;
import com.mockitodemo.model.Employee;
import com.mockitodemo.service.EmployeeService;
public class EmployeeController {
EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public List<Employee> getEmployee(String deptName) {
return employeeService.getEmployee(deptName);
}
public List<Employee> getDeveloper() {
return employeeService.getDeveloper();
}
public List<Employee> getTester() {
return employeeService.getTester();
}
}
MockitoDemoApplication.java
package com.mockitodemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MockitoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MockitoDemoApplication.class, args);
}
}
MockitoDemoApplicationTests.java
package com.mockitodemo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.mockitodemo.controller.EmployeeController;
import com.mockitodemo.model.Department;
import com.mockitodemo.service.EmployeeService;
@SpringBootTest
class MockitoDemoApplicationTests {
private static final String HR = "HR";
private static final String DEVELOPER = "Developer";
private static final String TESTER = "Tester";
@Test
void checkDepartmentForSuccess() {
Department department = new Department(DEVELOPER);
assertEquals(DEVELOPER, department.getDeptName());
}
@Test
void checkDepartmentForFailure() {
Department department = new Department(DEVELOPER);
assertNotEquals(TESTER, department.getDeptName());
}
@Test
void checkDeveloperEmployee() {
EmployeeService employeeService = new EmployeeService();
EmployeeController employeeController = new EmployeeController(employeeService);
assertEquals(2, employeeController.getDeveloper().size());
}
@Test
void checkEmployeeForException() {
EmployeeService employeeService = new EmployeeService();
EmployeeController employeeController = new EmployeeController(employeeService);
Assertions.assertThrows(IllegalArgumentException.class, () -> employeeController.getEmployee("Account"));
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.mockito-demo</groupId>
<artifactId>mockito-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mockito-demo</name>
<description>Demo project for mockito framework</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Run the Mockito Junit Test

See the Junit Test Report

Recommended Articles
- How does Spring Boot work with examples?
- How to create Spring Boot project?
- What are bean scopes in Spring?
- Learn hibernate java
- Hibernate interview questions in java