Controller에서 테스트 되는 내용은 이렇게 볼 수 있습니다.
@Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).
@WebMvcTest(value = {RandomMatchController.class},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
}
)
@AutoConfigureMockMvc(addFilters = false)
class RandomMatchControllerTest {
@Autowired
private MockMvc mockMvc;
}
@TestConfiguration
@Import({CustomOAuth2UserService.class, DefaultOAuth2UserServiceConfig.class,
CustomAuthenticationEntryPoint.class,
RedirectAuthenticationSuccessHandler.class, RedirectAuthenticationFailureHandler.class})
public class WebMvcTestWithSecurityDefaultConfig {
}
@WebMvcTest(ArticleController.class)
@Import(WebMvcTestWithSecurityDefaultConfig.class)
public class ArticleControllerWithSecurityTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@BeforeEach
private void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
@WithMockUser(username = "username", authorities = {"article.create"})
void writeArticle_whenHasAuthority_then200() throws Exception {
@Test
void writeArticle_whenNotAuthenticated_then401() throws Exception {
ArticleDto articleDto = ArticleDto.builder()
.title("title")
.date(LocalDate.now().plusDays(1))
.matchConditionDto(MatchConditionDto.builder()
.placeList(List.of())
.timeOfEatingList(List.of())
.wayOfEatingList(List.of())
.build())
.content("content")
.anonymity(false)
.participantNumMax(1)
.contentCategory(ContentCategory.MEAL)
.build();
mockMvc.perform(post("/api/articles")
.contentType(MediaType.APPLICATION_JSON).content(
new ObjectMapper().registerModule(new JavaTimeModule())
.writeValueAsString(articleDto)))
.andDo(print())
.andExpect(status().isUnauthorized());
}