본문 바로가기

봄보라

Spring Boot 에서 JUnit5 , MockMvc 를 이용하여 JSon 응답 값 검증하기

전 포스팅으로 Spring Boot 기반에서 JUnit5 를 이용하여 테스트 진행법을 작성했다

 

이번에는 기존 포스팅에서 실수로 빼먹은 응답 값 유효성 검증 방법을 작성한다

 

GET 요청
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.MockMvc;

@Autowired
private MockMvc mvc;

@Test
@DisplayName("GET 요청")
public void callGetTest() throws Exception{
  this.mvc.perform(get("/info")
                   .param("id", "3"))
                   .andExpect(status().isOk());
}

 

JUnit5 를 이용하여 기본적인 GET 방식 요청하는 방법이다

 

브라우저에서 http://url?id=3 의 형식과 동일하다

 

GET 응답 (정상)
{
     "nm" : "봄즈",
     "age" : 20,
     "auth" : "admin"

위의 GET 방식으로 요청 시 정상적인 아이디라면 위와 같은 JSon 형식의 응답을 전송한다

 

GET 응답 (비정상)
{
     "nm" : null,
     "age" : null,
     "auth" : null

잘못된 아이디로 요청 시 위와같이 null 값으로 응답이 온다

 

 

이런 형식일 때 Spring Boot 환경에서 JUnit5 를 이용해 응답의 유효성을 검사하려면 아래 방식처럼 진행하면 된다

 

GET 응답 검증
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.notNullValue;

@Autowired
private MockMvc mvc;

@Test
@DisplayName("GET 요청")
public void callGetTest() throws Exception{
  this.mvc.perform(get("/info")
                   .param("id", "3"))
                   .andExpect(status().isOk())
                   .andExpect(jsonPath("$.nm", notNullValue())
                   .andExpect(jsonPath("$.age", notNullValue())
                   .andExpect(jsonPath("$.auth", notNullValue());
}

 

간단한 JSon 응답 검증 예제이다

 

정상 응답일 경우 null 값이 아니므로 notNullValue() 를 이용해 검증하고 있다

 

GET 응답 검증
import java.util.Arrays;

  this.mvc.perform(get("/info")
                   .param("id", "3"))
                   .andExpect(status().isOk())
                   .andExpect(jsonPath("$.nm", notNullValue())
                   .andExpect(jsonPath("$.age", notNullValue())
                   .andExpect(jsonPath("$.auth", notNullValue())
                   .andExpect(jsonPath("$.auth", is(in(Arrays.asList("admin", "user"))));

만약 JSon 응답 값 중 auth 값은 'admin', 'user' 둘 중 하나만 정상이라고 할 경우 위처럼 유효성 검사를 추가할 수 있다

 

 

여기까지 간단하게 Spring Boot 환경에서 JUnit5 와 MockMvc 를 이용하여 응답 값을 검증하는 법을 마무리한다

 

 

참고 솔루션 : 봄즈