[MockTest] Body에 자꾸 Null이 들어간다. 해결 방법

Walter Mitty·2023년 5월 30일
0

등록 API에서 RequestDTO에 값들을 잘 담아서 보내는데 자꾸 null이 들어가서 400에러가 났다.

Error Code

@Test
    void 자주묻는질문_등록_수정() throws Exception {

        String accessToken = "access_token";
        String result = "자주묻는질문 등록/수정 완료";

        FaqRegistRequest request = FaqRegistRequest.builder()
            .faqTitle("치실, 치간칫솔, 칫솔질 중 어떤 것을 먼저 해야 되나요?")
            .faqContent("순서는 상관 없고 선호하는대로 하면 됩니다.")
            .faqId(1) // 없으면 등록, 있으면 수정
            .build();

        doNothing().when(faqApplicationService).registFaq(request);

        mockMvc.perform(
            post("/faq/regist")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header("Authorization", accessToken)
        )
            .andExpect(status().isOk())
            .andExpect(jsonPath("code").value(200))
            .andExpect(jsonPath("message").value(SuccessMessage.SUCCESS_MSG))
            .andExpect(jsonPath("data").value(result))
            .andDo(document("faq/regist",
                getDocumentRequest(),
                getDocumentResponse(),
                requestFields(
                    fieldWithPath("faqTitle").type(JsonFieldType.STRING).description("자주묻는질문 제목"),
                    fieldWithPath("faqContent").type(JsonFieldType.STRING).description("자주묻는질문 내용"),
                    fieldWithPath("faqId").type(JsonFieldType.NUMBER).description("관리자 고유번호")
                ),
                responseFields(
                    fieldWithPath("code").type(JsonFieldType.NUMBER).description("결과 코드"),
                    fieldWithPath("message").type(JsonFieldType.STRING).description("결과 메시지"),
                    fieldWithPath("data").type(JsonFieldType.STRING).description("결과 데이터")
                )
            ));
        verify(faqApplicationService).registFaq(any(FaqRegistRequest.class));
    }

Success Code

전부 다 볼 필요는 없어서 해당 부분만 보자면, .content(objectMapper.writeValueAsString(request))
Json 문자열로 변환하는 과정이 꼭 필요하다.

mockMvc.perform(
      post("/faq/regist")
        .content(objectMapper.writeValueAsString(request)) // 이부분이 빠져서다! Json 문자열로 변환하는 과정이다.
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .header("Authorization", accessToken)
)

0개의 댓글