@PutMapping("/rest/posts/{id}")
public ResponseEntity greetingSubmit(@PathVariable("id") Long id,
@RequestBody @Valid PostRequestDto post, BindingResult bindingResult,
HttpServletResponse response) throws IOException {
//post.setAuthor(((postService.findById(id)).getAuthor())); // 작성자 -> postService.update로 옮기기
if (bindingResult.hasErrors()) {
response.sendRedirect("/post/detail");
return new ResponseEntity(HttpStatus.FOUND);
}
PostResponseDto postResponseDto = postService.update(id, post);
return new ResponseEntity(postResponseDto, HttpStatus.CREATED);
}
유효성 검사에 실패하면 /post/detail로 redirect한다.
HTTP 상태 코드는 302다.
유효성 검사를 통과하면 글을 수정하고(postService.update 호출) HTTP 상태 코드는 201이다.
@Test
public void greetingSubmit_validationFail_redirect() throws Exception{ // 유효성 검사 실패 후 redirect
PostRequestDto postRequestDto=new PostRequestDto();
postRequestDto.setAuthor("iu");
mockMvc.perform(put("/rest/posts/{id}", 1)
.with(csrf())
.contentType("application/json")
.content(objectMapper.writeValueAsString(postRequestDto)))
.andDo(print())
.andExpect(status().isFound()) // 302
.andExpect(redirectedUrl("/post/detail"))
.andExpect(status().is3xxRedirection()); // redirection 여부
}
status().isFound()는 302
status().is3xxRedirection()은 redirection 여부
참고 👇
https://stackoverflow.com/questions/29085295/spring-mvc-restcontroller-and-redirect
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302
반응형
'Test > Junit' 카테고리의 다른 글
[MockMvc] Pageable (0) | 2022.09.17 |
---|---|
[Error] Internal Error occurred. org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests (1) | 2022.09.12 |
Cannot resolve symbol 'WithMockUser' (0) | 2022.08.30 |
JUnit5 (0) | 2022.01.27 |