ํ๊ฒฝ
- Spring boot 2.7.1
- Spring Security
- JUnit 5
Controller ํ ์คํธ๋ฅผ ํ๊ธฐ์ํด ๋ถํ์ํ ์์กด์ฑ๋ค์ ๊ฑท์ด๋ด๊ณ WebMvcTest ์ด๋ ธํ ์ด์ ์ ๋ถ์ฌ์ ์ปจํธ๋กค๋ฌ ๋ ์ด์ด๋ง ๊ฐ๋ณ๊ณ ๋น ๋ฅด๊ฒ ํ ์คํธ๋ฅผ ์งํํ ์ ์์ต๋๋ค.
WebMvcTest ์ด๋ ธํ ์ด์ ์ ๋ถ์ด๊ฒ ๋๋ฉด, MVC ํ ์คํธ๋ฅผ ์ํ ์์กด์ฑ๋ค์ด Spring Contetxt์ ์ฌ๋ผ๊ฐ๊ฒ ๋ฉ๋๋ค.
Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).
@WebMvcTest๋ WebSecurityConfigurerAdapter, WebMvcConfigurer๋ฅผ ๋น๋กฏํ @ControllerAdvice, @Controller๋ฅผ ์ฝ์ต๋๋ค. ์ฆ @Component, @Service, @Repository๋ ์ค์บ ๋์์ด ์๋๋๋ค.
ํ์ฌ Spring Security ์ค์ ์๋ JWT์ ์ฌ์ฉํ๊ธฐ ์ํ ๋น๋ค์ด ๋ฑ๋ก๋์ด ์๋ ์ํ์ ๋๋ค.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public JwtTokenUtil jwtTokenUtil() {
return new JwtTokenUtil();
}
@Bean
public PasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
return new JwtAuthenticationFilter(jwtTokenUtil(), authenticationManagerBean(), new ObjectMapper());
}
...
Spring Security ์ค์ ์ WebMvcTest์ ์ค์บ๋์์ ํฌํจ๋๋ฏ๋ก ๋ด๋ถ์ ์๋ ๋น๋ค์ ์ฝ์ ์๊ฐ ์์ด์ ์๋์ ๊ฐ์ ์๋ฌ๊ฐ ๋ฐ์ํฉ๋๋ค.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jwtAuthenticationFilter' defined in class path resource [me/iseunghan/todolist/config/SecurityConfig.class]:.....
ํด๊ฒฐ๋ฐฉ๋ฒ
Controller ๋ ์ด์ด ํ ์คํธ์ ์ค์ ์ ๋๊ธฐ ์ํด Security ์ค์ ์ ์ค์บ ๋์์์ ์ ์ธ ์ํต๋๋ค.
@WebMvcTest(controllers = AdminApiController.class,
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
classes = SecurityConfig.class
)}
)
public class AdminApiControllerTest {
}