Slice test chỉ load một phần của ApplicationContext — nhanh hơn @SpringBootTest và isolate layer cần test.
@WebMvcTest — test controller layer:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mvc;
@MockBean UserService service;
@Test
void getUser_returnsJson() throws Exception {
when(service.find(1L)).thenReturn(new User(1L, "Alice"));
mvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}@DataJpaTest — test repository layer:
@DataJpaTest
class UserRepositoryTest {
@Autowired UserRepository repo;
@Test
void findByEmail_found() {
repo.save(new User("alice@ex.com"));
assertThat(repo.findByEmail("alice@ex.com")).isPresent();
}
}Các slice khác: @JsonTest, @WebFluxTest, @RestClientTest, @DataMongoTest.
Khi dùng gì:
- Controller logic → @WebMvcTest.
- Query/repository → @DataJpaTest + Testcontainers cho DB thật.
- Full flow → @SpringBootTest.
Slice tests load only one slice of the ApplicationContext — faster than @SpringBootTest and isolate the layer under test.
@WebMvcTest — test the controller layer:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mvc;
@MockBean UserService service;
@Test
void getUser_returnsJson() throws Exception {
when(service.find(1L)).thenReturn(new User(1L, "Alice"));
mvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}@DataJpaTest — test the repository layer:
@DataJpaTest
class UserRepositoryTest {
@Autowired UserRepository repo;
@Test
void findByEmail_found() {
repo.save(new User("alice@ex.com"));
assertThat(repo.findByEmail("alice@ex.com")).isPresent();
}
}Other slices: @JsonTest, @WebFluxTest, @RestClientTest, @DataMongoTest.
When to use which:
- Controller logic → @WebMvcTest.
- Queries/repositories → @DataJpaTest + Testcontainers for a real DB.
- Full flow → @SpringBootTest.