본문 바로가기

Spring Boot

[Spring Boot] Spring Boot Test에서 JsonPath 사용하기

728x90

 

Spring Boot는 RESTful API 테스트를 용이하게 하기 위해 다양한 테스트 지원 기능을 제공합니다. 그 중 하나가 JsonPath를 사용하여 JSON 응답을 검증하는 것입니다. JsonPath는 JSON 데이터를 탐색하고 원하는 데이터를 추출할 수 있는 XPath와 유사한 구문을 제공합니다.

JsonPath란?

JsonPath는 JSON 문서에서 데이터를 추출하는 데 사용되는 표준화된 경로 언어입니다. 이를 통해 JSON 데이터 구조 내의 특정 필드나 값을 손쉽게 찾아낼 수 있습니다. 예를 들어, JSON 객체에서 특정 키의 값을 추출하거나 배열 내의 특정 요소를 선택할 수 있습니다.

주요 기능

  • 경로 표현식: JsonPath는 JSON 데이터 구조에서 특정 요소를 지정하는 경로 표현식을 제공합니다.
  • 필터링: 배열에서 특정 조건을 만족하는 요소만 선택할 수 있습니다.
  • 데이터 추출: JSON 구조에서 원하는 데이터를 손쉽게 추출할 수 있습니다.

예제 코드

1. 컨트롤러 작성

테스트할 간단한 RESTful API를 작성합니다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @GetMapping("/users")
    public List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        users.add(new User(1, "John Doe", "john.doe@example.com"));
        users.add(new User(2, "Jane Smith", "jane.smith@example.com"));
        return users;
    }

    public static class User {
        private int id;
        private String name;
        private String email;

        public User(int id, String name, String email) {
            this.id = id;
            this.name = name;
            this.email = email;
        }

        // Getters and setters omitted for brevity
    }
}

2. 테스트 작성

이제, JsonPath를 사용하여 컨트롤러의 응답을 테스트하는 코드를 작성합니다.

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.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGetAllUsers() throws Exception {
        mockMvc.perform(get("/users"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].id").value(1))
                .andExpect(jsonPath("$[0].name").value("John Doe"))
                .andExpect(jsonPath("$[0].email").value("john.doe@example.com"))
                .andExpect(jsonPath("$[1].id").value(2))
                .andExpect(jsonPath("$[1].name").value("Jane Smith"))
                .andExpect(jsonPath("$[1].email").value("jane.smith@example.com"));
    }
}

3. 테스트 실행

위의 테스트 코드는 /users 엔드포인트를 호출하고, JSON 응답에서 각 사용자의 id, name, email 필드를 검증합니다.

결론

Spring Boot 테스트에서 JsonPath를 사용하면 JSON 응답 데이터를 손쉽게 검증할 수 있습니다. 이는 RESTful API를 테스트할 때 매우 유용하며, 코드의 가독성과 유지보수성을 높이는 데 큰 도움이 됩니다.