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:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
</dependencies>

4. Spring Boot Mockito Junit 5 Example

// Model
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters, setters, constructors, etc.
}
// Repository Interface
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
// Service layer
@Service
public class EmployeeService {
    @Autowired
    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.*;
@ExtendWith(MockitoExtension.class)
public class EmployeeServiceTest {
    @Mock
    private EmployeeRepository repository;
    @InjectMocks
    private EmployeeService service;
    @Test
    public void testGetEmployeeDetails() {
        Employee emp = new Employee();
        emp.setId(1L);
        emp.setName("John Doe");
        when(repository.findById(1L)).thenReturn(java.util.Optional.of(emp));
        Employee result = service.getEmployeeDetails(1L);
        assertEquals(emp, result);
    }
}

Output:

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.


Comments