JAVA · 테스트
슬라이스 테스트 (@WebMvcTest)
웹 레이어만 로드하여 컨트롤러를 빠르게 테스트합니다.
테스트중급WebMvcTestMockMvcMockBean슬라이스테스트
핵심 설명
웹 레이어만 로드하여 컨트롤러를 빠르게 테스트합니다.
Java code
// @WebMvcTest(UserController.class)
// class UserControllerTest {
// @Autowired
// MockMvc mockMvc;
//
// @MockBean // Spring 컨텍스트에 Mock 주입
// UserService userService;
//
// @Test
// @DisplayName("GET /users/{id} — 200 OK")
// void getUser_found() throws Exception {
// given(userService.findById("1"))
// .willReturn(new UserDTO("1", "홍길동", "hong@test.com"));
//
// mockMvc.perform(get("/users/1")
// .accept(MediaType.APPLICATION_JSON))
// .andExpect(status().isOk())
// .andExpect(jsonPath("$.name").value("홍길동"))
// .andExpect(jsonPath("$.email").value("hong@test.com"));
// }
//
// @Test
// @DisplayName("POST /users — 201 Created")
// void createUser() throws Exception {
// String json = "{\"name\":\"홍길동\",\"email\":\"hong@test.com\"}";
//
// mockMvc.perform(post("/users")
// .contentType(MediaType.APPLICATION_JSON)
// .content(json))
// .andExpect(status().isCreated())
// .andExpect(header().exists("Location"));
// }
//
// @Test
// @DisplayName("GET /users/{id} — 404 Not Found")
// void getUser_notFound() throws Exception {
// given(userService.findById("999"))
// .willThrow(new NotFoundException("사용자 없음"));
//
// mockMvc.perform(get("/users/999"))
// .andExpect(status().isNotFound());
// }
// }
class Main {
public static void main(String[] args) {
System.out.println("@WebMvcTest: Controller + Filter + ControllerAdvice만 로드");
System.out.println("Service, Repository는 @MockBean으로 대체");
}
}학습 팁
@WebMvcTest는 @SpringBootTest보다 10배 이상 빠릅니다. 컨트롤러 로직 검증에는 항상 슬라이스 테스트를 사용하세요.
주의할 점
@MockBean은 Spring 컨텍스트의 빈을 대체합니다. @Mock(Mockito)과 다르니 혼동하지 마세요.
자주 묻는 질문
슬라이스 테스트 (@WebMvcTest)란 무엇인가요?
웹 레이어만 로드하여 컨트롤러를 빠르게 테스트합니다.
슬라이스 테스트 (@WebMvcTest) 학습 시 주의할 점은 무엇인가요?
@MockBean 은 Spring 컨텍스트의 빈을 대체합니다. @Mock (Mockito)과 다르니 혼동하지 마세요.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.