PostsApiControllerTest의 2개 테스트 메소드에 임의의 사용자 인증을 추가
// test/web/PostsApiController.java
@Test
/* @WithMockUser(roles="USER")
: 인증된 모의 (가짜) 사용자를 만들어서 사용
roles에 권한을 추가할 수 있음
즉, 어노테이션으로 인해 ROLE_USER 권한을 가진 사용자가 API를 요청하는 것과 동일한 효과 */
@WithMockUser(roles="USER")
public void Posts_등록된다() throws Exception {
...
}
@Test
@WithMockUser(roles="USER")
public void Posts_수정된다() throws Exception {
...
}
@WithMockUser가 MockMvc에서만 작동하기 때문에 PostsApiController에 MockMvc를 사용하도록 해야 함
@SpringBootTest에서 MockMvc를 사용하는 방법 코드로 변경
// test/web/PostsApiControllerTest.java
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PostsApiControllerTest {
...
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
/* @Before
: 매번 테스트가 시작되기 전에 MockMvc 인스턴스를 생성 */
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
...
@Test
@WithMockUser(roles="USER")
public void Posts_등록된다() throws Exception {
...
// when
/* mvc.perform
: 생성된 MockMvc를 통해 API를 테스트
본문(Body) 영역은 문자열로 표현하기 위해 ObjectMapper를 통해 문자열 JSON으로 변환 */
mvc.perform(post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(new ObjectMapper().writeValueAsString(requestDto)))
.andExpect(status().isOk());
// then
List<Posts> all = postsRepository.findAll();
assertThat(all.get(0).getTitle()).isEqualTo(title);
assertThat(all.get(0).getContent()).isEqualTo(content);
}
@Test
@WithMockUser(roles="USER")
public void Posts_수정된다() throws Exception {
...
// when
mvc.perform(put(url)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(new ObjectMapper().writeValueAsString(requestDto)))
.andExpect(status().isOk());
// then
List<Posts> all = postsRepository.findAll();
assertThat(all.get(0).getTitle()).isEqualTo(expectedTitle);
assertThat(all.get(0).getContent()).isEqualTo(expectedContent);
}
}
다시 gradle로 테스트를 수행해 보면 실패 테스트가 줄어든 것을 확인 가능
🌱 문제 3. @WebMvcTest에서 CustomOAuth2UserService를 찾을 수 없음
"No qualifying bean of type 'com.gagyeong.book.springboot.config.auth.CustomOAuth2UserService'"
문제 1번과 다른 점은 @WebMvcTest를 사용한다는 점
문제 1번은 스프링 시큐리티 설정은 잘 작동했지만, @WebMvcTest는 CustomOAuth2UserService를 스캔하지 않기 때문
@WebMvcTest는 WebSecurityConfigureAdapter, WebMvcConfigurer를 비롯한 @ControllerAdvice, @Controller는 스캔 대상이나, @Repository, @Service, @Component는 스캔 대상이 아님
그러니 SecurityConfig는 읽었지만, SecurityConfig를 생성하기 위해 필요한 CustomOAuth2UserService는 읽을 수가 없어 에러 발생