[Junit TEST 코드] @RequestBody Param 전송 및 Object <-> Json String 변환

반응형
728x90
반응형

테스트 코드 작성 로그 -2

 

TODO

- POST 메서드 호출

- @RequestBody param 전송

- DTO(Object) 를 Json String 으로 변환 (with Jackson)

- API Response 의 "data" 특정 key 값의 결과만 꺼내오기

- Json String 을 List<DTO> 로 변환 (With jackson)

 

 

테스트 코드

import com.couchbase.client.java.json.JsonObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
class CommVendorControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    @DisplayName("닉네임 조회")
    void nickname_select_success() throws Exception {
        /* param set */
        SearchDto searchDto = new SearchDto();
        searchDto.setSearchKey("nickname");
        searchDto.setSearchWord("kimseohae");

        MvcResult result = mockMvc.perform(post("/getNickname")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(toJson(searchDto)))
                .andExpect(status().isOk())
                .andReturn();

        /* get result  */
        String response = result.getResponse().getContentAsString();
        Map<String, Object> dataString = JsonPath.parse(response).read("$.data");

        String body = toJson(dataString.get("resultList"));
        List<NicknameDto> resultList = toNicknameDto(body);

        Assertions.assertThat(resultList.get(0).getNickname()).isEqualTo("kimseohae");
    }

    private <T> String toJson(T data) throws JsonProcessingException {
        return objectMapper.writeValueAsString(data);
    }

    private List<NicknameDto> toNicknameDto(String json) throws JsonProcessingException {
        return objectMapper.readValue(json , new TypeReference<List<NicknameDto>>(){});
    }

}

 

1) MockMvc post

...
    MvcResult result = mockMvc.perform(post("/getNickname")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(toJson(searchDto)))
            .andExpect(status().isOk())
            .andReturn();
...

 

2) toJosn(Dto) 메서드 호출

private <T> String toJson(T data) throws JsonProcessingException {
    return objectMapper.writeValueAsString(data);
}

 

3) "data"에 해당하는 결과 얻기

 Map<String, Object> dataString = JsonPath.parse(response).read("$.data");

 

4) 위 String을 Dto로 변환하기

        ...
        String body = toJson(dataString.get("resultList"));
        List<NicknameDto> resultList = toNicknameDto(body);

        Assertions.assertThat(resultList.get(0).getNickname()).isEqualTo("kimseohae");
    }


    private List<NicknameDto> toNicknameDto(String json) throws JsonProcessingException {
        return objectMapper.readValue(json , new TypeReference<List<NicknameDto>>(){});
    }

 

 

 

반응형

Designed by JB FACTORY