Framework/스프링 라이브러리
[TEST] Controller Test에서 ObjectMapper 사용하기
simDev1234
2022. 9. 20. 23:11
| ObjectMapper로 Json으로 파싱
- 방법
(1) 테스트 클래스 안에 @Autowired로 test-container의 ObjectMapper를 주입한다.
(2) 테스트 메소드 안에 contentType과 content를 지정한다.
contentType에 MediaType.APPLICATION_JSON을 지정하고,
content에 object -> json형식의 string으로 반환하는 objectMapper의 writeValueAsString(Object value)를 쓴다.
@Autowired
ObjectMapper objectMapper;
@Test
void createXX() throws Exception {
// given 생략
// then
mockMvc.perform(post("/path")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(
new CreateXX.Request(1L, 1234L)
))
);
}
(3) 경로 확인하기
// 객체
jsonPath("$.userId").value(1L)
// 배열
jsonPath("$[0].userId").value(1L)
jsonPath("$[1].userId").value(2L)
jsonPath("$[2].userId").value(3L)
- Json-Path 작성 방법 상세
https://github.com/json-path/JsonPath
GitHub - json-path/JsonPath: Java JsonPath implementation
Java JsonPath implementation. Contribute to json-path/JsonPath development by creating an account on GitHub.
github.com
[ 참고 및 출처 ]
부트캠프 강의 내용