@SpringBootTest khởi động full ApplicationContext — load toàn bộ bean, auto-config, database... như production.
java
@SpringBootTest
@AutoConfigureMockMvc
class OrderIntegrationTest {
@Autowired MockMvc mvc;
@Autowired OrderRepository repo;
@Test
@Transactional
void createOrder_persistsToDb() throws Exception {
mvc.perform(post("/api/orders")
.contentType(APPLICATION_JSON)
.content("{\"product\":\"widget\",\"qty\":2}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").exists());
}
}| Unit test | @SpringBootTest | |
|---|---|---|
| Context | Không có Spring | Full ApplicationContext |
| Tốc độ | Nhanh (~ms) | Chậm (~5-30s startup) |
| DB | Mock/in-memory | Real hoặc Testcontainers |
Modes:
- webEnvironment = MOCK (default) — MockMvc.
- webEnvironment = RANDOM_PORT — server thật, dùng TestRestTemplate.
Best practice: ít dùng (chậm). Ưu tiên slice tests (@WebMvcTest, @DataJpaTest).
@SpringBootTest boots the full ApplicationContext — loads all beans, auto-configs, databases like production.
java
@SpringBootTest
@AutoConfigureMockMvc
class OrderIntegrationTest {
@Autowired MockMvc mvc;
@Autowired OrderRepository repo;
@Test
@Transactional
void createOrder_persistsToDb() throws Exception {
mvc.perform(post("/api/orders")
.contentType(APPLICATION_JSON)
.content("{\"product\":\"widget\",\"qty\":2}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").exists());
}
}| Unit test | @SpringBootTest | |
|---|---|---|
| Context | No Spring | Full ApplicationContext |
| Speed | Fast (~ms) | Slow (~5-30s startup) |
| DB | Mock/in-memory | Real or Testcontainers |
Modes:
- webEnvironment = MOCK (default) — MockMvc.
- webEnvironment = RANDOM_PORT — real server, use TestRestTemplate.
Best practice: use sparingly (slow). Prefer slice tests (@WebMvcTest, @DataJpaTest).