Test/Junit

[MockMvc] 테스트 시 redirect 여부 확인

잔망루피 2022. 9. 17. 23:30
반응형
@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://www.blog.ecsimsw.com/entry/SpringBootTest-redirect%EB%A5%BC-%ED%85%8C%EC%8A%A4%ED%8A%B8%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95

 

SpringBootTest / redirect 여부를 확인하는 방법

상황 1. "/room/create/{roomName}"을 요청하면 서버에선 room을 생성 2. 생성된 db id와 함께 "/game/create/{roomId}로 redirect 테스트 코드 @Transactional @SpringBootTest @AutoConfigureMockMvc class Room..

www.blog.ecsimsw.com

 

https://stackoverflow.com/questions/29085295/spring-mvc-restcontroller-and-redirect

 

Spring MVC @RestController and redirect

I have a REST endpoint implemented with Spring MVC @RestController. Sometime, depends on input parameters in my controller I need to send http redirect on client. Is it possible with Spring MVC @

stackoverflow.com

 

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302

 

302 Found - HTTP | MDN

The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header. A browser redirects to this page but search engines don't update their

developer.mozilla.org

 

반응형