[테스트] 컨트롤러 (Controller) 테스트 할 때 andExpect() 예외를 던질 때 문구 검사

손경이·2024년 2월 20일
0

2024.02.19
[테킷 백엔드] 프로젝트 - alcoholfriday
환경 - 스프링부트 3.2.1, 자바 JDK17
작업 - 장바구니에 상품 추가 테스트


💡 컨트롤러 (Controller) 테스트 할 때 andExpect() 예외를 던질 때 문구 검사

- andExpect().value()

  • resultActions.andExpect()에서 json 응답
{"httpMethod":"POST","path":"/v1/carts","message":"존재하지 않는 상품입니다."}
  • 테스트 할 때 예외 문구 검증
    • json응답에서 "message" 필드의 값이 "존재하지 않는 상품입니다."를 검증
.andExpect(jsonPath("$.message").value("존재하지 않는 상품입니다."));

- 전체 코드

@Test
    @DisplayName("존재하지 않는 상품일 경우")
    @WithAccount
    void addCartList_notFoundItem() throws Exception {
        // when
        ResultActions resultActions = mvc
                .perform(post("/v1/carts")
                        .contentType(MediaType.APPLICATION_JSON)
                        .characterEncoding("UTF-8")
                        .content("""
                                {
                                  "cartRequestList": [
                                    {
                                      "itemId": "20",
                                      "quantity": "2"
                                    }
                                  ]
                                }
                                """)
                )
                .andDo(print());

        // then
        resultActions
                .andExpect(status().isNotFound())
                .andExpect(handler().handlerType(CartController.class))
                .andExpect(handler().methodName("addCartList"))
                .andExpect(jsonPath("$.message").value("존재하지 않는 상품입니다."));
    }

참고

ChatGPT

0개의 댓글