spring
[junit5] MockMvc 테스트중 NestedServletException 통과시키기
sup2is
2020. 8. 26. 10:48
애플리케이션 컨트롤러 코드는 다음과 같을 수 있다
@PostMapping("/token")
public ResponseEntity<JsonResult<AuthenticationResponseDto>> generateJwtToken
(@RequestBody AuthenticationRequestDto authenticationRequestDto) {
//bla bla ...
if(!passwordEncoder.matches(authenticationRequestDto.getPassword(), user.getPassword())) {
throw new BadCredentialsException("Password not matched");
}
//bla bla ...
}
이 코드에서 throw new BadCredentialsException("Password not matched"); 를 발생시키면 mockmvc 테스트 도중 NestedServletException 이 발생한다. 때문에 테스트를 실패하는데 junit5에서 다음과 같은 방법으로 NestedServletException 내부에서 발생한 exception을 검사할 수 있도록 다음과 같은 메서드를 제공한다.
org.assertj.core.api.Assertions.assertThatThrownBy(
() -> mvc.perform(get("/api/scope")).andExpect(status().isOk()))
.hasCause(new AccessDeniedException("Access is denied"));
이런식으로 테스트하면 테스트를 통과할 수 있다.