특정 수의 컨트롤러가있는 스프링 부트 MVC 애플리케이션을 개발 중입니다. 내 루트 컨트롤러는 : 나는 성공적으로 컨트롤러 MVC 테스트를 구현 한스프링 부트 WebMvc 테스트에 스프링 보안을 포함하지 않음
@Controller
@RequestMapping("/")
public class RootController {
@GetMapping
public String showStartPage() {
log.info("GET: Show home page");
return "index";
}
}
. 내 RootController에 대한 시험은 다음과 같습니다
이@RunWith(SpringRunner.class)
@WebMvcTest(RootController.class)
public class RootControllerMvcTest {
@Autowired
private MockMvc mvc;
@Test
public void testRoot() throws Exception {
mvc.perform(get("/").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk())
.andExpect(view().name("index"));
}
}
문제 : 봄 보안 인증 및 권한 부여를 도입 할 때
그러나, 모든 MVC 컨트롤러 테스트 고장. 루트 컨트롤러 테스트에 대한 어설 션 오류는 다음과 같습니다
java.lang.AssertionError: Status
Expected :200
Actual :401
내 보안 구성은 다음과 같습니다
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/fonts/*").permitAll()
.antMatchers("/user/**").hasAuthority("ADMIN")
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("email")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/")
.permitAll()
.and()
.rememberMe();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
해결책
:@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RootControllerMvcTest {
...
}
: 다음
, 내가 가진 문제를 해결하기 위해 관리
이 경우 내 테스트는 전체 응용 프로그램 컨텍스트를로드합니다.
내 질문은 :
- 어떻게이 컨트롤러의 인증 및 권한 부여 과정과 시험에만 논리에서 분리 내 MVC 테스트를 유지할 수 있습니까?
- 인증 및 권한 부여 구현을 테스트하는 가장 좋은 방법은 무엇입니까? 이 목적으로 @SpringBootTest를 사용해야합니까?
- 내 컨트롤러와 보안 논리를 별도로 테스트하는 것이 좋습니까?
고맙습니다.
[테스트 스프링 부트 보안 간단하게] (http://stackoverflow.com/questions/31812054/testing-spring-boot-security-simply) –
감사합니다. 유용한 링크입니다. 하지만 우선, MockMvc로 컨트롤러를 테스트 할 수 있는지 그리고 스프링 보안을 사용하지 않고 컨트롤러를 테스트 할 수 있는지를 알아 내려고합니다. –