Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Spring Boot » Mockito Framework Tutorial for Unit testing | Mockito unit testing spring boot

  • Nelson Mandela Biography in Hindi | Nelson Mandela Day
    Nelson Mandela Biography in Hindi | Nelson Mandela Day Biography
  • Prithviraj Chauhan Biography in Hindi | पृथ्वीराज चौहान जीवनी हिंदी
    Prithviraj Chauhan Biography in Hindi | पृथ्वीराज चौहान जीवनी हिंदी Biography
  • Unicef day
    Unicef day is celebrated on December 11 | Speech on unicef day General Knowledge
  • Christmas Day Celebration
    Christmas Day Celebration | Story about Christmas day Festival
  • Kapil Sharma Show, Comedy Show in Hindi
    Kapil Sharma Show, Comedy Show in Hindi Biography
  • जन्माष्टमी व्रत पूजा विस्तार से | दही हांडी | Krishna Janmashtami Puja
    जन्माष्टमी व्रत पूजा विस्तार से, दही हांडी: Krishna Janmashtami Puja Festival
  • Hima Das Biography | भारतीय धाविका हिमा दास का जीवन परिचय
    Hima Das Biography | भारतीय धाविका हिमा दास का जीवन परिचय Biography
  • Newton's laws of Motion, State and Explained, Formula
    Newton’s laws of Motion, State and Explained, Formula Science

Mockito Framework Tutorial for Unit testing | Mockito unit testing spring boot

Posted on July 30, 2022November 18, 2022 By GeekCer Education No Comments on Mockito Framework Tutorial for Unit testing | Mockito unit testing spring boot
Mockito unit testing spring boot

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?
    • Stub
    • Fake
    • Mock
  • What are the benefits of Mockito Framework?
  • Unit tests with Mockito Framework example program

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.

  1. No handwriting is required for Mockito code.
  2. Mockito provides returned values, which are significant from a validation perspective.
  3. To identify the cause of an exception, Mockito offers stack traces and exception validation.
  4. Most importantly, the annotations are supported. As a result, you won’t have to write as much or any XML code.
  5. Since runtime creation of mock objects. So you can safely rename and refactor the method names of interfaces without changing the test code.
  6. 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

Run Mockito Framework Junit Test

See the Junit Test Report

Report of Mockito Framework Junit Test

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

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Important, Spring, Spring Boot Tags:Junit rest api testing using mockito, Mockito controller test spring boot

Post navigation

Previous Post: DBMS in Hindi | DBMS क्या है? | DBMS की विशेषताएं और प्रकार
Next Post: Difference between Git Merge and Git Rebase | Git Rebase vs Git Merge

More Related Articles

What is Agriculture Agriculture (कृषि) से जुड़े महत्वपूर्ण प्रश्न और उत्तर Important
Linux Commands With Example | Linux commands cheat sheet Linux Commands With Example | Linux commands cheat sheet Important
Spring Boot Tutorial Spring Boot Tutorial Spring Boot
What is International Monetary Fund (I.M.F.) What is International Monetary Fund (I.M.F.)? Important
Difference Between get() and load() in Hibernate with example Difference Between get() and load() in Hibernate with example Differences
JSON The Data Interchange Standard Format JSON The Data Interchange Standard Format Important

Leave a Reply Cancel reply

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

  • National Farmers Day in Hindi | राष्ट्रीय किसान दिवस पर निबंध | चौधरी चरण सिंह जयंती
  • Human rights day in Hindi: 10 दिसंबर ह्यूमन राइट्स डे
  • Unicef day is celebrated on December 11 | Speech on unicef day
  • Indian Navy Day: जल सेना दिवस कब और क्यों मनाया जाता है?
  • P V Sindhu Biography in Hindi, Badminton, State, Caste पी. वी. सिंधु जीवन परिचय, कहानी, राज्य, जाति
  • Draupadi Murmu Biography In Hindi | द्रौपदी मुर्मू की जीवनी
  • IPv4 Vs IPv6 | Difference between IPv4 and IPv6
    IPv4 Vs IPv6 | Difference between IPv4 and IPv6 Differences
  • TCP/IP Model, Full Form, Layers and their Functions
    TCP/IP Model, Full Form, Layers and their Functions Networking
  • OSI Model | 7 Layers of OSI Model in Computer network
    OSI Model | 7 Layers of OSI Model in Computer network, Functions Networking
  • Difference between TCP and UDP
    Difference between TCP and UDP | TCP vs UDP examples Differences
  • Difference between Internet and Intranet
    Difference between Internet and Intranet Differences
  • Similarities and difference between OSI and TCP/IP model
    OSI vs TCP/IP Model, Similarities and difference between OSI and TCP/IP model Networking
  • Network kya hai (नेटवर्क क्या है)
    Network kya hai (नेटवर्क क्या है) Networking
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved