// 특정 컨트롤러만 로드 (권장)@WebMvcTest(PostController.class)classPostControllerTest{@AutowiredprivateMockMvc mockMvc;@AutowiredprivateObjectMapper objectMapper;// JSON 직렬화@MockBeanprivatePostUseCase postUseCase;// 서비스 레이어 Mock 필수@Test@DisplayName("[GET] /api/posts/{id} - 정상 조회")voidgetPost_success()throwsException{// Givengiven(postUseCase.findById(1L)).willReturn(newPostResponse(1L,"제목","PUBLISHED"));// When & Then mockMvc.perform(get("/api/posts/1").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1L)).andExpect(jsonPath("$.title").value("제목")).andDo(print());}@Test@DisplayName("[POST] /api/posts - 게시글 생성 시 201 반환")voidcreatePost_success()throwsException{// GivenCreatePostRequest request =newCreatePostRequest("제목","내용");given(postUseCase.create(any())).willReturn(newPostResponse(1L,"제목","DRAFT"));// When & Then mockMvc.perform(post("/api/posts").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(request))).andExpect(status().isCreated()).andExpect(jsonPath("$.id").value(1L));}@Test@DisplayName("[GET] /api/posts/{id} - 없는 ID → 404 반환")voidgetPost_notFound_returns404()throwsException{given(postUseCase.findById(999L)).willThrow(newResourceNotFoundException("Post not found")); mockMvc.perform(get("/api/posts/999")).andExpect(status().isNotFound());}}
// 방법 1: 필터 제거 (인증 없이 테스트)@WebMvcTest(PostController.class)@AutoConfigureMockMvc(addFilters =false)classPostControllerTest{...}// 방법 2: @WithMockUser로 인증된 사용자 시뮬레이션@Test@WithMockUser(username ="user@example.com", roles ="USER")voidgetPost_authenticated_returns200()throwsException{ mockMvc.perform(get("/api/posts/1")).andExpect(status().isOk());}// 방법 3: Security 설정 자체를 제외@WebMvcTest(value =PostController.class, excludeAutoConfiguration =SecurityAutoConfiguration.class)classPostControllerTest{...}