Spring Boot Mockito Service Layer Example

1. Overview

Service layer testing ensures the business logic of your application is correctly implemented without being affected by external factors like databases or external services. In this guide, we'll use Mockito to mock repository interactions while testing our service layer.

2. Development Steps

1. Create a Spring Boot application.

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

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

4. Run the tests to validate the outcomes.

3. Maven Dependencies

    <!-- Spring Boot Starter Data JPA -->
    <!-- H2 Database for testing -->

4. Spring Boot Mockito Service Layer Example

// Model
public class Employee {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters, setters, constructors, etc.
// Repository layer
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
// Service layer
public class EmployeeService {
    private EmployeeRepository repository;
    public Employee saveEmployee(Employee employee) {
        return repository.save(employee);
// 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;
public class EmployeeServiceTest {
    private EmployeeRepository repository;
    private EmployeeService service;
    public void testSaveEmployee() {
        Employee emp = new Employee();
        emp.setName("John Doe");
        Employee savedEmployee = service.saveEmployee(emp);
        Assertions.assertEquals("John Doe", savedEmployee.getName());


The test testSaveEmployee will pass, confirming that the EmployeeService's save method works as expected.

Code Explanation:

- We've used the @ExtendWith(MockitoExtension.class) annotation to integrate Mockito with JUnit 5.

- The @Mock annotation is used to mock the EmployeeRepository, ensuring our service tests are not interacting with a real database.

- @InjectMocks auto-injects the EmployeeRepository mock into the EmployeeService.

- In the test, we defined the behavior of the mocked repository using Mockito.when(...).thenReturn(...).

- We then invoke the service method and assert the outcome to ensure correctness.

5. Conclusion

Testing the service layer in a Spring Boot application is crucial to verify the correctness of the business logic without being affected by external dependencies. Mockito offers a powerful and easy way to mock these dependencies, ensuring that our tests are focused and isolated.