Skip to main content

Command Palette

Search for a command to run...

Bài 11: Spring Boot Testing

Published
4 min readView as Markdown

1. Các loại kiểm thử trong Spring Boot

Kiểm thử là một phần quan trọng trong phát triển phần mềm, giúp đảm bảo rằng ứng dụng hoạt động đúng đắn và ổn định. Trong Spring Boot, có ba loại kiểm thử chính:

  1. Unit Test: Kiểm thử đơn vị tập trung vào việc kiểm tra các thành phần nhỏ nhất của ứng dụng như các phương thức hoặc các lớp đơn lẻ. Các bài kiểm thử đơn vị thường sử dụng các công cụ như JUnit và Mockito.

  2. Integration Test: Kiểm thử tích hợp kiểm tra sự tương tác giữa các thành phần của ứng dụng. Spring Boot cung cấp các công cụ để dễ dàng thực hiện kiểm thử tích hợp, như Spring TestContext Framework.

  3. End-to-End Test: Kiểm thử từ đầu đến cuối kiểm tra toàn bộ ứng dụng từ phía người dùng đến cơ sở dữ liệu. Các công cụ như Selenium hoặc RestAssured thường được sử dụng cho loại kiểm thử này.

2. Sử dụng Spring Boot Test, MockMvc và TestRestTemplate

Spring Boot cung cấp các công cụ mạnh mẽ để thực hiện kiểm thử, bao gồm Spring Boot Test, MockMvcTestRestTemplate.

2.1. Sử dụng Spring Boot Test

Spring Boot Test là một phần của Spring Test Framework, cung cấp các annotation và tiện ích để thực hiện kiểm thử.

Ví dụ: Unit Test với Spring Boot Test và JUnit

// GreetingService.java
package com.example.myapp.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    public String greet(String name) {
        return "Hello, " + name;
    }
}

// GreetingServiceTests.java
package com.example.myapp.service;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class GreetingServiceTests {

    @Test
    public void testGreet() {
        GreetingService greetingService = new GreetingService();
        String result = greetingService.greet("Spring");
        assertEquals("Hello, Spring", result);
    }
}

Ví dụ: Integration Test với Spring Boot Test và @SpringBootTest

// MyApplicationTests.java
package com.example.myapp;

import com.example.myapp.service.GreetingService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
public class MyApplicationTests {

    @Autowired
    private GreetingService greetingService;

    @Test
    public void contextLoads() {
        String result = greetingService.greet("Spring Boot");
        assertEquals("Hello, Spring Boot", result);
    }
}

2.2. Sử dụng MockMvc

MockMvc là một công cụ mạnh mẽ để kiểm thử các thành phần web trong Spring MVC. Nó cho phép bạn mô phỏng các request HTTP và xác nhận các response mà không cần khởi động server.

Ví dụ: Kiểm thử controller với MockMvc

// GreetingController.java
package com.example.myapp.controller;

import com.example.myapp.service.GreetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @Autowired
    private GreetingService greetingService;

    @GetMapping("/greet")
    public String greet(@RequestParam String name) {
        return greetingService.greet(name);
    }
}

// GreetingControllerTests.java
package com.example.myapp.controller;

import com.example.myapp.service.GreetingService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(GreetingController.class)
public class GreetingControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private GreetingService greetingService;

    @Test
    public void testGreet() throws Exception {
        given(greetingService.greet("Spring")).willReturn("Hello, Spring");

        mockMvc.perform(get("/greet?name=Spring"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, Spring"));
    }
}

2.3. Sử dụng TestRestTemplate

TestRestTemplate là một công cụ để kiểm thử các endpoint RESTful. Nó cung cấp các phương thức để gửi request HTTP và kiểm tra các response.

Ví dụ: Kiểm thử endpoint RESTful với TestRestTemplate

// MyApplication.java
package com.example.myapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

// GreetingController.java
package com.example.myapp.controller;

import com.example.myapp.service.GreetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @Autowired
    private GreetingService greetingService;

    @GetMapping("/greet")
    public String greet(@RequestParam String name) {
        return greetingService.greet(name);
    }
}

// GreetingService.java
package com.example.myapp.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    public String greet(String name) {
        return "Hello, " + name;
    }
}

// GreetingControllerIntegrationTests.java
package com.example.myapp.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GreetingControllerIntegrationTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testGreet() {
        ResponseEntity<String> response = restTemplate.getForEntity("/greet?name=Spring Boot", String.class);
        assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
        assertThat(response.getBody()).isEqualTo("Hello, Spring Boot");
    }
}

3. Cấu hình và thực hiện các bài kiểm tra

Spring Boot cung cấp các công cụ và cấu hình mặc định để thực hiện kiểm tra một cách dễ dàng. Bạn chỉ cần chú ý đến việc viết các bài kiểm tra và cấu hình các dependency cần thiết trong pom.xml hoặc build.gradle.

Cấu hình pom.xml với Maven:

<dependencies>
    <!-- Spring Boot Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Cấu hình build.gradle với Gradle:

dependencies {
    // Spring Boot Test
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

4. Kết luận

Trong bài viết này, chúng ta đã tìm hiểu về các loại kiểm thử trong Spring Boot, bao gồm Unit Test, Integration Test và End-to-End Test. Chúng ta cũng đã thấy cách sử dụng các công cụ như Spring Boot Test, MockMvc và TestRestTemplate để thực hiện các bài kiểm tra. Kiểm thử là một phần không thể thiếu trong quá trình phát triển phần mềm, giúp đảm bảo rằng ứng dụng hoạt động đúng đắn và ổn định.

Trong bài viết tiếp theo, chúng ta sẽ tìm hiểu về cách truy cập dữ liệu trong Spring Boot, sử dụng Spring Data JPA để thực hiện các thao tác CRUD với cơ sở dữ liệu.

More from this blog

devngu

169 posts