Cụm bài Test trong Spring Boot: 1. Unit test với JUnit và Mockito · 2. Slice test và Testcontainers
Phần lớn bug của một REST service nằm ở chỗ nối: JSON map sai, validation không chạy, query sai trên DB thật, security trả 500 thay vì 403. Bài này chỉ cách test các chỗ nối đó bằng slice test, integration test và Testcontainers mà bộ test vẫn nhanh. Mọi ví dụ lấy từ lab Spring Boot 4.0.3: mvn test chạy 29 test, 28 pass, 1 skip.
Sơ đồ tóm tắt:
flowchart TD
A{"Cần trả lời câu gì?"} -->|"Tầng HTTP"| C["@WebMvcTest"]
A -->|"Repository và SQL"| D["@DataJpaTest + flush/clear"]
A -->|"Cả luồng"| E["@SpringBootTest"]
E --> F{"Cần HTTP thật?"}
F -->|"Không"| G["MockMvc"]
F -->|"Có"| H["RANDOM_PORT"]
D --> I["Testcontainers + @ServiceConnection"]
E --> I
I --> J["Ít cấu hình, cache context"]
1. Bản đồ các loại test trong Spring Boot
Ý chính: chọn loại test theo câu hỏi bạn cần trả lời, không theo thói quen. Slice cho câu hỏi về một tầng, @SpringBootTest cho câu hỏi về cả luồng.
| Annotation | Nạp gì | Trả lời câu hỏi |
|---|---|---|
| (không gì, chỉ Mockito) | không có Spring | logic nghiệp vụ đúng chưa (phần 1) |
@WebMvcTest(XController.class) |
controller đó, @ControllerAdvice, Jackson, validation, filter, Spring Security |
URL, status, JSON, validation, mã lỗi |
@DataJpaTest |
entity, repository, EntityManager, DataSource (mặc định DB nhúng) |
mapping, query, constraint |
@JsonTest |
Jackson ObjectMapper và JacksonTester |
format ngày giờ, tên field, @JsonInclude |
@SpringBootTest + @AutoConfigureMockMvc |
toàn bộ context, không server thật | luồng đầy đủ qua security chain thật |
@SpringBootTest(webEnvironment = RANDOM_PORT) |
toàn bộ context + server thật | hành vi HTTP thật: filter của container, cookie, chuyển thread |
Slice nhanh vì bỏ qua bean không liên quan. Bean @Service, @Component thường không được nạp vào @WebMvcTest; bạn cấp chúng bằng @MockitoBean.
2. @WebMvcTest: test tầng HTTP
Ý chính: @WebMvcTest kiểm phần mà unit test không thấy: URL map đúng method, @Valid chạy, JSON ra đúng field, exception map đúng status. Service được thay bằng @MockitoBean.
@WebMvcTest(UserController.class)
class UserControllerWebMvcTest {
@Autowired MockMvc mvc;
@MockitoBean UserService userService;
@Test
@WithMockUser
void invalidBodyReturnsProblemDetailWithAllFieldErrors() throws Exception {
mvc.perform(post("/api/v1/users").with(csrf()).contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":" ","email":"not-an-email","password":"123"}"""))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.errors[*].field", hasItem("email")));
verify(userService, never()).create(any());
}
}
Bốn test trong lab kiểm: 201 + header Location + không có field password; 400 với tất cả lỗi field; DuplicateResourceException → 409; JSON hỏng → 400 chứ không phải 500.
3. @DataJpaTest: test repository trên DB
Ý chính: @DataJpaTest chạy JPA với DB nhúng, mỗi test trong một transaction được rollback. Muốn thấy SQL thật và lỗi thật, gọi flush() để đẩy SQL xuống DB và clear() để lần đọc sau không lấy từ persistence context.
@Test
void replaceKeepsPermissionsRowsAndRewritesJoinTable() {
Permission a = permissions.save(new Permission("A", "/api/v1/a", "GET", "X"));
Permission b = permissions.save(new Permission("B", "/api/v1/b", "GET", "X"));
Role r = new Role("HR");
r.getPermissions().add(a);
roles.save(r);
em.flush(); em.clear(); // ép SQL thật, nếu không chỉ test cache cấp 1
Role loaded = roles.findWithPermissionsById(r.getId()).orElseThrow();
loaded.replacePermissions(Set.of(permissions.getReferenceById(b.getId())));
em.flush(); em.clear();
Role again = roles.findWithPermissionsById(r.getId()).orElseThrow();
assertThat(again.getPermissions()).extracting(Permission::getName).containsExactly("B");
assertThat(permissions.count()).isEqualTo(2); // A vẫn còn, chỉ mất liên kết
}
Không có clear(), findWithPermissionsById trả lại đúng object trong bộ nhớ, và test xanh kể cả khi mapping join table sai. Persistence context và cache cấp 1 có ở bài JPA persistence context và N+1.
4. @SpringBootTest: MockMvc hay server thật
Ý chính: @SpringBootTest + MockMvc nạp cả context và đi qua security chain thật, nhưng request chạy trên thread của test, không có server. RANDOM_PORT chạy Tomcat thật và gửi HTTP thật; chậm hơn nhưng giống production hơn.
MockMvc (MOCK) |
RANDOM_PORT + RestTestClient / TestRestTemplate |
|
|---|---|---|
| Server | không, gọi DispatcherServlet trực tiếp |
Tomcat thật trên cổng ngẫu nhiên |
| Thread | cùng thread với test | thread của server |
@Transactional trên test |
rollback được request | không rollback (transaction khác thread) |
| Kiểm được | controller, filter Spring, security | thêm: container filter, cookie thật, timeout, encoding |
RestTestClient là client test mới trong Spring Framework 7, dùng được cả với MockMvc lẫn server thật. TestRestTemplate vẫn còn trong Boot 4 nhưng tách sang module riêng; tài liệu khoá học nói nó bị “thay thế” là chưa chính xác.
5. Test security bằng JWT thật
Ý chính: integration test cho phân quyền nên dùng token thật, ký bằng đúng JwtEncoder của ứng dụng, đi qua đúng filter chain. Một TestDataFactory tạo user với đúng quyền test cần và cấp token cho họ.
@TestComponent
public class TestDataFactory {
// ... repositories, PasswordEncoder, JwtService qua constructor
public void reset() {
tokens.deleteAll(); users.deleteAll(); roles.deleteAll(); permissions.deleteAll();
}
/** permissionSpecs như "GET /api/v1/users/{id}". Rỗng = role không có quyền nào. */
public User user(String email, String password, String roleName, String... permissionSpecs) { ... }
public String accessToken(User u, String roleName) {
return jwt.issueAccessToken(u.getEmail(), List.of(roleName));
}
}
Các kịch bản trong AuthFlowIntegrationTest (12 test, @Nested theo nhóm):
| Nhóm | Kịch bản | Mong đợi |
|---|---|---|
| Authentication | sai mật khẩu; không token; token bị sửa chữ ký | 401, có WWW-Authenticate: Bearer, body application/problem+json |
| Authorization | role có permission khớp path pattern; role rỗng | 200; 403 |
| MethodSecurity | có permission URL nhưng thiếu role ADMIN; ADMIN xoá chính mình | 403 do @PreAuthorize; 400 |
| RefreshRotation | xoay vòng; dùng lại token cũ; logout; thiếu cookie | token mới; 401 và thu hồi cả family; cookie Max-Age=0; 401 |
Bài này chỉ bàn cách test. Cấu hình resource server giải thích ở Spring Security cho REST API, refresh token xoay vòng và AuthorizationManager theo permission ở refresh token xoay vòng và phân quyền; lý thuyết JWT ở bài xác thực.
Toàn bộ AuthFlowIntegrationTest (rút gọn phần lặp)
@SpringBootTest
@AutoConfigureMockMvc
@Import(TestDataFactory.class)
class AuthFlowIntegrationTest {
@Autowired MockMvc mvc;
@Autowired TestDataFactory data;
@Autowired RefreshTokenRepository tokens;
User admin;
@BeforeEach
void setUp() {
data.reset();
admin = data.user("admin@example.dev", "secret-pass-1", "ADMIN", "GET /api/v1/users/{id}", "POST /api/v1/users");
}
@Nested
class Authorization {
@Test
void permissionMatchingPathPatternIs200() throws Exception {
mvc.perform(get("/api/v1/users/" + admin.getId())
.header("Authorization", "Bearer " + data.accessToken(admin, "ADMIN")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.email").value("admin@example.dev"));
}
@Test
void roleWithoutPermissionIs403() throws Exception {
User viewer = data.user("viewer@example.dev", "secret-pass-1", "VIEWER");
mvc.perform(get("/api/v1/users/" + admin.getId())
.header("Authorization", "Bearer " + data.accessToken(viewer, "VIEWER")))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.status").value(403));
}
}
@Nested
class RefreshRotation {
@Test
void reusingARotatedTokenRevokesTheWholeFamily() throws Exception {
String first = login();
String second = mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", first)))
.andReturn().getResponse().getCookie("refresh_token").getValue();
mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", first)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.detail").value("refresh token reuse detected"));
// token mới nhất của người dùng thật cũng chết theo family (thu hồi đã commit dù trả 401)
mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", second)))
.andExpect(status().isUnauthorized());
assertThat(tokens.findAll()).allMatch(RefreshToken::isRevoked);
}
}
}
Test cuối chỉ đúng vì test không @Transactional: service dùng noRollbackFor để việc thu hồi family được commit dù trả 401, và test kiểm điều đó bằng cách đọc lại từ DB.
Trong @WebMvcTest, khi không cần token thật, dùng post-processor của spring-security-test: .with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))) tạo sẵn JwtAuthenticationToken mà không ký gì cả.
6. Testcontainers: DB thật trong Docker
Ý chính: Testcontainers khởi động PostgreSQL/MySQL thật trong Docker cho test; @ServiceConnection (Boot 3.1+) cho Boot tự đọc URL, user, password từ container. Test bắt được khác biệt mà H2 che đi.
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // giữ datasource, không thay bằng H2
@Testcontainers(disabledWithoutDocker = true) // máy không có Docker: skip, không fail
class UserRepositoryPostgresTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");
@Autowired UserRepository users;
@Test
void uniqueEmailIsCaseSensitiveInPostgresSoTheServiceMustNormalize() {
users.saveAndFlush(new User("A", "an@example.dev", "h", User.Gender.OTHER));
users.saveAndFlush(new User("B", "AN@example.dev", "h", User.Gender.OTHER)); // UNIQUE so byte, không so "email"
assertThat(users.count()).isEqualTo(2);
assertThat(users.existsByEmailIgnoreCase("An@Example.DEV")).isTrue();
}
}
Trạng thái thật: test này biên dịch được nhưng bị skip khi mình chạy, vì Docker engine trên máy đang dừng. Kết quả nêu trong test (PostgreSQL cho lưu hai email khác hoa thường) là hành vi đã biết của UNIQUE trên varchar với collation mặc định, chưa được xác nhận bằng lần chạy này.
Vì sao nên dùng DB thật thay H2 (cú pháp, hàm ngày giờ, khoá, collation) đã có trade-off ở bài kế hoạch triển khai Spring Boot; bài này không nhắc lại.
Giữ Testcontainers nhanh: một container cho cả bộ test
- Static container trong một class trừu tượng dùng chung, hoặc một
@TestConfigurationkhai báo@Bean @ServiceConnection PostgreSQLContainer: mọi test class cùng context dùng chung một container thay vì mỗi class một cái. - Khởi động một lần cho cả JVM: khai báo container trong
static {}và gọistart(), Ryuk dọn khi JVM thoát. - Reuse giữa các lần chạy local:
withReuse(true)+testcontainers.reuse.enable=truetrong~/.testcontainers.properties; không dùng trên CI. - Image nhỏ, pin version:
postgres:17-alpine, không dùnglatest, để test không đổi hành vi khi image mới ra. - Chạy local bằng container: Boot 3.1+ cho phép một class
TestApplicationgọiSpringApplication.from(App::main).with(ContainersConfig.class).run(args)để chạy app dev với DB trong Docker. - Testcontainers 2.x (đi với Boot 4): artifact đổi tên thành
testcontainers-postgresql,testcontainers-junit-jupiter, class PostgreSQL nằm ở package mớiorg.testcontainers.postgresql. - Máy dev dùng Docker không ở socket mặc định (Colima, OrbStack…) thì đặt
DOCKER_HOSThoặcdocker.hosttrong~/.testcontainers.properties.
7. Giữ bộ test nhanh: context caching
Ý chính: Spring cache application context giữa các test class có cùng cấu hình. Mỗi khác biệt (tổ hợp @MockitoBean, @TestPropertySource, profile, @Import) tạo khoá cache mới và một lần khởi động context mới.
- Gom
@MockitoBeanvào một base class hoặc giữ chúng giống nhau giữa các test cùng loại. - Tránh
@DirtiesContext; nó vứt context và buộc khởi động lại. Thường có cách dọn dữ liệu rẻ hơn. - Bật log
org.springframework.test.context.cache=DEBUGđể xem số context được tạo và tỉ lệ hit. - Cache mặc định giữ tối đa 32 context (
spring.test.context.cache.maxSize); context bị đẩy ra sẽ đóng, container gắn với nó cũng có thể dừng. - Phân nhóm: unit và slice chạy mỗi lần build (
surefire), integration với Testcontainers có thể tách sangfailsafe(*IT.java) để chạy song song trên CI. Pipeline GitHub Actions chạy cả hai nhóm bằng./mvnw verify, có Testcontainers trên runner, có ở CI/CD cho backend.
8. Những thay đổi test trong Spring Boot 4
Ý chính: Boot 4 tách các annotation test theo module và cần starter test riêng cho từng công nghệ; @MockBean đã bị xoá. Code test cũ thường chỉ cần đổi import và dependency.
| Thay đổi | Boot 3.x | Boot 4 |
|---|---|---|
| Starter test | một spring-boot-starter-test |
thêm spring-boot-starter-webmvc-test, -data-jpa-test, -security-oauth2-resource-server-test… (đã kèm starter-test) |
| Package slice | org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest |
org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; @DataJpaTest ở ...boot.data.jpa.test.autoconfigure |
| Mock bean | @MockBean (deprecated từ 3.4) |
@MockitoBean, @MockitoSpyBean (Spring Framework, có từ 6.2 / Boot 3.4) |
| JUnit | 5 | 6 (API Jupiter giữ nguyên) |
| HTTP client test | TestRestTemplate, WebTestClient |
thêm RestTestClient; TestRestTemplate vẫn còn ở module riêng |
Bài tập
- Viết
@WebMvcTestchoDELETE /api/v1/users/{id}của lab, chứng minh khiUserService.deletenémIllegalArgumentExceptionthì API trả 400 vớiapplication/problem+json. Có cần@EnableMethodSecuritytrong slice không? - Thiết kế lại bộ test của lab để mọi test integration chạy trên PostgreSQL qua Testcontainers với một container dùng chung, và đếm số Spring context được tạo.
Lời giải gợi ý
Bài 1. Slice không nạp SecurityConfig, nên @EnableMethodSecurity không có hiệu lực và @PreAuthorize("hasRole('ADMIN')") bị bỏ qua: test này chỉ kiểm mapping lỗi, không kiểm quyền.
@Test
void selfDeleteIs400() throws Exception {
doThrow(new IllegalArgumentException("You cannot delete your own account"))
.when(userService).delete(eq(1L), any());
mvc.perform(delete("/api/v1/users/1").with(jwt()).with(csrf()))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON));
}
jwt() cấp Authentication để controller nhận được tham số auth. Muốn kiểm @PreAuthorize trong slice thì @Import một config nhỏ có @EnableMethodSecurity; nhưng kiểm quyền thật đã có ở AuthFlowIntegrationTest.
Bài 2. Tạo @TestConfiguration(proxyBeanMethods = false) class PostgresConfig với @Bean @ServiceConnection PostgreSQLContainer postgres(); mọi @SpringBootTest dùng chung @Import(PostgresConfig.class) và không thêm @MockitoBean riêng, để chỉ có một context và một container. @DataJpaTest là cấu hình khác nên có context riêng (thêm một container nếu nó cũng import config này). Đếm context bằng log org.springframework.test.context.cache=DEBUG. Lời giải này chưa chạy, vì Docker engine trên máy đang dừng.
Ghi nhớ
- Chọn được giữa unit,
@WebMvcTest,@DataJpaTestvà@SpringBootTesttheo câu hỏi cần trả lời. - Giải thích được vì sao slice test không chứng minh quy tắc phân quyền, và test phân quyền thế nào.
- Biết vì sao cần
flush()/clear()trong@DataJpaTest, và vì sao vớiIDENTITYlỗi constraint ném ngay ởsave. - Kể được ba bug mà
@Transactionaltrên integration test che mất. - Giải thích được context caching và cách giữ bộ test có Testcontainers vẫn nhanh.
Câu hỏi phỏng vấn
Mid
@WebMvcTest khác @SpringBootTest thế nào?
@WebMvcTest chỉ nạp tầng web (controller, advice, Jackson, validation, security) và mock phần còn lại; @SpringBootTest nạp toàn bộ ứng dụng.
Slice nhanh và chỉ ra lỗi ở tầng HTTP. @SpringBootTest chậm hơn nhưng kiểm được luồng thật qua service, DB và security chain của bạn.
Vì sao gọi flush() và clear() trong @DataJpaTest?
flush() đẩy SQL xuống DB để constraint và mapping thật chạy; clear() xoá persistence context để lần đọc sau đi xuống DB chứ không lấy object trong bộ nhớ.
Thiếu chúng, test có thể xanh dù mapping sai, vì bạn chỉ đọc lại đúng object vừa lưu.
@MockitoBean và @Mock khác nhau thế nào?
@Mock là mock thuần Mockito trong unit test; @MockitoBean thay một bean trong Spring context bằng mock.
Dùng @MockitoBean trong slice/integration test. Mỗi tổ hợp @MockitoBean khác nhau làm Spring tạo context mới, nên dùng tiết kiệm.
Senior
Có nên đặt @Transactional trên integration test để rollback dữ liệu không?
Với MockMvc thì được nhưng che bug; với RANDOM_PORT thì không có tác dụng. Test quan trọng nên commit thật và tự dọn dữ liệu.
@Transactional trên test giữ transaction mở suốt, nên che LazyInitializationException, lỗi lúc commit và listener AFTER_COMMIT. Với server thật, request chạy ở thread khác nên không rollback. Thay bằng dọn dữ liệu trong @BeforeEach hoặc dữ liệu duy nhất cho mỗi test.
Bộ test Spring Boot của team mất 15 phút. Bạn điều tra thế nào?
Đếm số Spring context được tạo trước tiên: log của context cache cho biết bao nhiêu lần khởi động và vì sao.
- Gom
@MockitoBean, property, profile để các class dùng chung context; bỏ@DirtiesContext. - Một container Testcontainers dùng chung thay vì mỗi class một cái.
- Đẩy logic xuống unit test; tách integration test sang
failsafevà chạy song song trên CI.
Bạn test phân quyền của một REST API dùng JWT thế nào?
Bằng @SpringBootTest + MockMvc với token thật ký bằng JwtEncoder của ứng dụng, qua đúng filter chain, với user có đúng quyền từng test cần.
Kiểm cả 401 (không token, token hỏng, hết hạn), 403 (thiếu quyền, thiếu role ở method security) và 200. Slice test với jwt() hay @WithMockUser chỉ chứng minh controller đúng, không chứng minh quy tắc.
Khi nào chọn H2, khi nào Testcontainers?
Testcontainers với đúng DB production cho mọi test chạm query, constraint, khoá; H2 chỉ khi cần thật nhanh cho mapping đơn giản và chấp nhận rủi ro khác dialect.
H2 khác ở cú pháp, hàm ngày giờ, collation và hành vi khoá. Cái giá của Testcontainers là cần Docker và thời gian khởi động, giảm bằng container dùng chung.
Từ vựng tiếng Anh
| Term | Phát âm | Nghĩa | Ví dụ câu tiếng Anh dùng trong phỏng vấn |
|---|---|---|---|
| test slice | /test slaɪs/ | lát cắt ứng dụng để test | “A test slice loads only the web layer, so it starts in milliseconds.” |
| integration test | /ˌɪn.təˈɡreɪ.ʃən test/ | test nhiều thành phần với nhau | “Authorization rules need an integration test with the real filter chain.” |
| context caching | /ˈkɑːn.tekst ˈkæʃ.ɪŋ/ | cache Spring context giữa test | “Every distinct set of mocked beans breaks context caching.” |
| persistence context | /pɚˈsɪs.təns ˈkɑːn.tekst/ | bộ nhớ đệm entity của JPA | “Clear the persistence context, or you’ll read the object back from memory.” |
| roll back | /roʊl bæk/ | huỷ thay đổi | “With a random port the test transaction can’t roll back the server’s work.” |
| throwaway container | /ˈθroʊ.ə.weɪ kənˈteɪ.nɚ/ | container dùng một lần | “Testcontainers gives each run a throwaway Postgres.” |
| service connection | /ˈsɝː.vɪs kəˈnek.ʃən/ | Boot tự lấy thông tin kết nối | “With a service connection Boot reads the JDBC URL straight from the container.” |
| flaky | /ˈfleɪ.ki/ | lúc xanh lúc đỏ | “Shared mutable test data is the usual cause of flaky integration tests.” |
| post-processor | /poʊst ˈprɑː.ses.ɚ/ | bước xử lý thêm cho request test | “The jwt() post-processor fakes an authenticated request.” |
| test fixture | /test ˈfɪks.tʃɚ/ | dữ liệu dựng sẵn cho test | “Our test data factory builds a fixture with exactly the permissions a test needs.” |
Ghi chép dựa trên tài liệu khoá học của Hỏi Dân IT, viết lại và bổ sung theo cách hiểu của mình.