Master Unit Testing in Spring Boot | JUnit, Mockito | Step-by-Step Tutorial

3 min read 9 hours ago
Published on Jan 10, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of writing unit tests for a Spring Boot application using JUnit and Mockito. Whether you're a beginner or looking to enhance your existing skills, this step-by-step guide will help you understand crucial testing concepts and how to implement them effectively. We will cover basic utility functions, API endpoints, Spring Security testing, and the use of in-memory databases like H2 for testing in CI/CD pipelines.

Step 1: Familiarize with Sample Project

Before diving into unit testing, get acquainted with the sample Spring Boot project.

  • Clone the project from GitHub:
    Spring Boot Tutorials Repository
  • Open the project in your favorite IDE (e.g., IntelliJ, Eclipse).
  • Review the project structure, paying attention to the main application files, controllers, and services.

Step 2: Write the First Unit Test

Start by creating a simple unit test for a basic utility function.

  1. Locate the utility class you want to test.
  2. Create a test class in the src/test/java directory.
  3. Add dependencies for JUnit and Mockito in your pom.xml file:
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.9.0</version>
        <scope>test</scope>
    </dependency>
    
  4. Write a simple test method:
    @Test
    void testUtilityFunction() {
        // Arrange
        UtilityClass utility = new UtilityClass();
        
        // Act
        String result = utility.someMethod();
        
        // Assert
        assertEquals("Expected Result", result);
    }
    

Step 3: Using @SpyBean for Mocking Methods

Learn how to use @SpyBean to mock specific methods in your service classes.

  1. In your test class, annotate your service with @SpyBean.
    @SpyBean
    private MyService myService;
    
  2. Write a test case to stub a method:
    @Test
    void testServiceMethod() {
        // Arrange
        when(myService.methodToSpy()).thenReturn("Stubbed Response");
        
        // Act
        String response = myService.methodToSpy();
        
        // Assert
        assertEquals("Stubbed Response", response);
    }
    

Step 4: Unit Test for Controllers and API Endpoints

Now, let’s test your controllers and API endpoints.

  1. Create a test class for your controller.
  2. Use @MockMvc to simulate HTTP requests:
    @Autowired
    private MockMvc mockMvc;
    
  3. Write a test for an API endpoint:
    @Test
    void testGetApiEndpoint() throws Exception {
        mockMvc.perform(get("/api/endpoint"))
               .andExpect(status().isOk())
               .andExpect(content().string("Expected Response"));
    }
    

Step 5: Unit Test with Spring Security Test

Learn to test secured endpoints using Spring Security's @WithMockUser.

  1. Annotate your test class with @WebMvcTest.
  2. Use @WithMockUser to simulate an authenticated user:
    @WithMockUser(username = "admin", roles = {"ADMIN"})
    @Test
    void testSecuredEndpoint() throws Exception {
        mockMvc.perform(get("/secure/endpoint"))
               .andExpect(status().isOk());
    }
    

Step 6: Special In-Memory Database for Unit Tests

Utilize an in-memory database like H2 for testing.

  1. Add H2 dependency in your pom.xml:
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
    </dependency>
    
  2. Configure application properties for testing:
    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=password
    spring.h2.console.enabled=true
    
  3. Use H2 for testing your repositories.

Conclusion

In this tutorial, you've learned how to write unit tests using JUnit and Mockito in a Spring Boot application. You explored creating tests for utility functions, controllers, secured endpoints, and using an in-memory database for efficient testing. As you continue your journey, consider exploring advanced testing techniques and integrating these practices into your DevOps CI/CD workflows. Happy testing!