Spring Boot Mockito Junit 5 Example

1. Overview

In the world of Spring Boot, unit testing is a critical aspect of ensuring the validity and robustness of your application. Mockito, in combination with JUnit 5, offers a powerful toolset for mocking dependencies and creating tests. In this tutorial, we will discuss how to use Mockito and JUnit 5 to write JUnit tests in Spring boot applications.

2. Development Steps

1. Set up a new Spring Boot project.

2. Define the model, repository, and service layers.

3. Write a unit test for the service layer using Mockito and JUnit 5.

4. Run the tests and validate the outcomes.

3. Dependencies

Create a Spring Boot project and add the following dependencies:

4. Spring Boot Mockito Junit 5 Example

// Model
public class Employee {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters, setters, constructors, etc.
// Repository Interface
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
// Service layer
public class EmployeeService {
    private EmployeeRepository repository;
    public Employee getEmployeeDetails(Long id) {
        return repository.findById(id).orElse(null);
// Test class
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
public class EmployeeServiceTest {
    private EmployeeRepository repository;
    private EmployeeService service;
    public void testGetEmployeeDetails() {
        Employee emp = new Employee();
        emp.setName("John Doe");
        Employee result = service.getEmployeeDetails(1L);
        assertEquals(emp, result);


The test testGetEmployeeDetails will pass, ensuring that the EmployeeService's method retrieves the correct employee details.

Code Explanation:

- We set up a simple Spring Boot application with JPA for data persistence.

- The Employee model represents an entity in our system.

- We then define a repository using Spring Data JPA to handle our database operations.

- The EmployeeService contains our business logic and utilizes the repository.

- For testing, we mock the EmployeeRepository to isolate the service layer. This ensures that the test isn't dependent on database interactions.

- @ExtendWith(MockitoExtension.class) initializes Mockito in the JUnit 5 environment.

- The test verifies that given a certain repository behavior (mocked), the service behaves as expected.

5. Conclusion

Unit testing in Spring Boot applications is essential for verifying the correctness of our code, especially in layered architectures. By using Mockito alongside JUnit 5, we can effectively mock out dependencies and ensure that our service layer (or any other layer) behaves as expected under various conditions.