Skip to content

Ktor를 사용하여 Kotlin에서 RESTful API 만들기

코드 예제: tutorial-server-restful-api

사용된 플러그인: Routing라우팅은 서버 애플리케이션에서 들어오는 요청을 처리하기 위한 핵심 플러그인입니다.,Static Content스타일시트, 스크립트, 이미지 등과 같은 정적 콘텐츠를 서빙하는 방법을 알아봅니다., Content NegotiationContentNegotiation 플러그인은 두 가지 주요 목적을 수행합니다. 클라이언트와 서버 간의 미디어 유형 협상, 그리고 특정 형식으로 콘텐츠를 직렬화/역직렬화하는 것입니다., kotlinx.serialization

이 튜토리얼에서는 Kotlin과 Ktor를 사용하여 백엔드 서비스를 구축하는 방법을 설명하며, JSON을 생성하는 RESTful API 예제를 다룹니다.

이전 튜토리얼태스크 관리자(Task Manager) 애플리케이션을 빌드하며 Kotlin 및 Ktor를 통한 라우팅, 요청 처리, 파라미터 기초를 학습합니다.에서는 유효성 검사, 에러 처리, 단위 테스트의 기본 사항을 소개했습니다. 이 튜토리얼에서는 이러한 주제를 확장하여 작업을 관리하는 RESTful 서비스를 만들어 보겠습니다.

다음을 배울 수 있습니다:

  • JSON 직렬화를 사용하는 RESTful 서비스 생성.
  • 콘텐츠 협상(Content Negotiation)ContentNegotiation 플러그인은 두 가지 주요 목적을 수행합니다. 클라이언트와 서버 간의 미디어 유형 협상, 그리고 특정 형식으로 콘텐츠를 직렬화/역직렬화하는 것입니다. 과정 이해.
  • Ktor 내에서 REST API를 위한 라우트 정의.

사전 준비 사항

이 튜토리얼을 단독으로 진행할 수도 있지만, 요청을 처리하고 응답을 생성태스크 관리자(Task Manager) 애플리케이션을 빌드하며 Kotlin 및 Ktor를 통한 라우팅, 요청 처리, 파라미터 기초를 학습합니다.하는 방법을 배우기 위해 이전 튜토리얼을 먼저 완료하는 것을 강력히 권장합니다.

IntelliJ IDEA를 설치하는 것을 권장하지만, 원하는 다른 IDE를 사용해도 좋습니다.

RESTful 작업 관리자 시작하기

이 튜토리얼에서는 기존 작업 관리자를 RESTful 서비스로 다시 작성합니다. 이를 위해 여러 Ktor 플러그인플러그인은 직렬화, 콘텐츠 인코딩, 압축 등과 같은 공통 기능을 제공합니다.을 사용합니다.

기존 프로젝트에 수동으로 추가할 수도 있지만, 새 프로젝트를 생성한 다음 이전 튜토리얼의 코드를 단계적으로 추가하는 것이 더 간단합니다. 진행하면서 모든 코드를 다시 설명하므로 이전 프로젝트가 준비되어 있지 않아도 됩니다.

플러그인을 포함한 새 프로젝트 생성

  1. Ktor Project Generator로 이동합니다.

  2. Project artifact 필드에 프로젝트 아티팩트 이름으로 com.example.ktor-rest-task-app 를 입력합니다. Ktor Project Generator에서 프로젝트 아티팩트 이름 지정하기

  3. 플러그인 섹션에서 다음 플러그인을 검색하고 Add 버튼을 클릭하여 추가합니다:

    1. Content Negotiation
    2. kotlinx.serialization
    3. Static Content

    Ktor Project Generator에서 플러그인 추가하기 플러그인을 추가하면 프로젝트 설정 아래에 나열된 모든 플러그인을 확인할 수 있습니다. Ktor Project Generator의 플러그인 목록

  4. Download 버튼을 클릭하여 Ktor 프로젝트를 생성하고 다운로드합니다.

시작 코드 추가

  1. Ktor 프로젝트 생성, 열기 및 실행 튜토리얼에서 설명한 대로 IntelliJ IDEA에서 프로젝트를 엽니다.

  2. src/main/kotlin 으로 이동하여 model 이라는 하위 패키지를 생성합니다.

  3. model 패키지 안에 새 Task.kt 파일을 생성합니다.

  4. Task.kt 파일을 열고 우선순위를 나타내는 enum과 작업을 나타내는 class를 추가합니다:

    kotlin
    package com.example.model
    
    import kotlinx.serialization.Serializable
    
    enum class Priority {
        Low, Medium, High, Vital
    }
    
    @Serializable
    data class Task(
        val name: String,
        val description: String,
        val priority: Priority
    )

    이전 튜토리얼에서는 Task를 HTML로 변환하기 위해 확장 함수를 사용했습니다. 이번에는 Task 클래스에 kotlinx.serialization 라이브러리의 Serializable 타입 어노테이션을 지정합니다.

  5. Routing.kt 파일을 열고 기존 코드를 아래 구현으로 교체합니다:

    kotlin
    package com.example
    
    import com.example.model.*
    import io.ktor.server.application.*
    import io.ktor.server.http.content.*
    import io.ktor.server.response.*
    import io.ktor.server.routing.*
    
    fun Application.configureRouting() {
        routing {
            staticResources("static", "static")
    
            get("/tasks") {
                call.respond(
                    listOf(
                        Task("cleaning", "Clean the house", Priority.Low),
                        Task("gardening", "Mow the lawn", Priority.Medium),
                        Task("shopping", "Buy the groceries", Priority.High),
                        Task("painting", "Paint the fence", Priority.Medium)
                    )
                )
            }
        }
    }

    이전 튜토리얼과 마찬가지로 URL /tasks에 대한 GET 요청 라우트를 생성했습니다. 이번에는 작업 목록을 수동으로 변환하는 대신 단순히 목록을 반환하기만 합니다.

  6. IntelliJ IDEA에서 실행 버튼(IntelliJ IDEA 실행 아이콘)을 클릭하여 애플리케이션을 시작합니다.

  7. 브라우저에서 http://0.0.0.0:8080/tasks로 이동합니다. 아래와 같이 작업 목록의 JSON 버전을 확인할 수 있습니다:

  8. 브라우저 화면에 표시된 JSON 데이터

    상당히 많은 작업이 우리를 대신해 자동으로 처리되고 있음을 알 수 있습니다. 과연 내부에서는 어떤 일이 일어나고 있는 것일까요?

Content Negotiation 이해하기

브라우저를 통한 콘텐츠 협상

프로젝트를 생성할 때 Content NegotiationContentNegotiation 플러그인은 두 가지 주요 목적을 수행합니다. 클라이언트와 서버 간의 미디어 유형 협상, 그리고 특정 형식으로 콘텐츠를 직렬화/역직렬화하는 것입니다. 플러그인을 포함했습니다. 이 플러그인은 클라이언트가 렌더링할 수 있는 콘텐츠 유형을 살펴보고 현재 서비스가 제공할 수 있는 콘텐츠 유형과 일치시킵니다. 그래서 콘텐츠 협상(Content Negotiation) 이라는 용어가 사용됩니다.

HTTP에서 클라이언트는 Accept 헤더를 통해 자신이 렌더링할 수 있는 콘텐츠 유형을 알립니다. 이 헤더의 값은 하나 이상의 콘텐츠 유형입니다. 위의 경우 브라우저에 내장된 개발자 도구를 사용하여 이 헤더의 값을 확인할 수 있습니다.

다음 예시를 살펴보겠습니다:

text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7

*/*가 포함되어 있음에 유의하세요. 이 헤더는 HTML, XML 또는 이미지를 수락하지만 다른 모든 콘텐츠 유형도 수락함을 나타냅니다.

Content Negotiation 플러그인은 데이터를 브라우저로 다시 보낼 형식을 찾아야 합니다. 프로젝트에 생성된 코드를 살펴보면 src/main/kotlin 안에 다음 내용이 포함된 Serialization.kt 파일이 있습니다:

kotlin
fun Application.configureSerialization() {
    install(ContentNegotiation) {
        json()
    }
}

이 코드는 ContentNegotiation 플러그인을 설치하고 kotlinx.serialization 플러그인도 구성합니다. 이를 통해 클라이언트가 요청을 보낼 때 서버는 JSON으로 직렬화된 객체를 다시 보낼 수 있습니다.

브라우저로부터의 요청인 경우, ContentNegotiation 플러그인은 자신이 JSON만 반환할 수 있다는 것을 알고 있으며, 브라우저는 전송받은 모든 내용을 표시하려고 시도합니다. 따라서 요청이 성공합니다.

JavaScript를 통한 콘텐츠 협상

    프로덕션 환경에서는 일반적으로 브라우저에 JSON을 직접 표시하지 않습니다. 대신 브라우저에서 실행되는 JavaScript 코드가 요청을 보낸 다음, 반환된 데이터를 단일 페이지 애플리케이션(SPA)의 일부로 표시합니다. 일반적으로 이러한 종류의 애플리케이션은 React, Angular, 또는 Vue.js와 같은 프레임워크를 사용하여 작성됩니다.

  1. 이를 시뮬레이션하기 위해 src/main/resources/static 안에 있는 index.html 페이지를 열고 기본 콘텐츠를 다음으로 교체합니다:

    html
    <html>
    <head>
        <title>A Simple SPA For Tasks</title>
        <script type="application/javascript">
            function fetchAndDisplayTasks() {
                fetchTasks()
                    .then(tasks => displayTasks(tasks))
            }
    
            function fetchTasks() {
                return fetch(
                    "/tasks",
                    {
                        headers: { 'Accept': 'application/json' }
                    }
                ).then(resp => resp.json());
            }
    
            function displayTasks(tasks) {
                const tasksTableBody = document.getElementById("tasksTableBody")
                tasks.forEach(task => {
                    const newRow = taskRow(task);
                    tasksTableBody.appendChild(newRow);
                });
            }
    
            function taskRow(task) {
                return tr([
                    td(task.name),
                    td(task.description),
                    td(task.priority)
                ]);
            }
    
            function tr(children) {
                const node = document.createElement("tr");
                children.forEach(child => node.appendChild(child));
                return node;
            }
    
            function td(text) {
                const node = document.createElement("td");
                node.appendChild(document.createTextNode(text));
                return node;
            }
        </script>
    </head>
    <body>
    <h1>Viewing Tasks Via JS</h1>
    <form action="javascript:fetchAndDisplayTasks()">
        <input type="submit" value="View The Tasks">
    </form>
    <table>
        <thead>
        <tr><th>Name</th><th>Description</th><th>Priority</th></tr>
        </thead>
        <tbody id="tasksTableBody">
        </tbody>
    </table>
    </body>
    </html>

    이 페이지에는 HTML 폼과 빈 테이블이 포함되어 있습니다. 폼을 제출하면 JavaScript 이벤트 핸들러가 Accept 헤더를 application/json으로 설정하여 /tasks 엔드포인트로 요청을 보냅니다. 그런 다음 반환된 데이터를 역직렬화하여 HTML 테이블에 추가합니다.

  2. IntelliJ IDEA에서 재실행 버튼(IntelliJ IDEA 재실행 아이콘)을 클릭하여 애플리케이션을 다시 시작합니다.

  3. URL http://0.0.0.0:8080/static/index.html로 이동합니다. View The Tasks 버튼을 클릭하여 데이터를 가져올 수 있습니다:

    버튼과 작업이 HTML 테이블로 표시된 브라우저 창

GET 라우트 추가

이제 콘텐츠 협상 과정에 익숙해졌으므로, 이전 튜토리얼태스크 관리자(Task Manager) 애플리케이션을 빌드하며 Kotlin 및 Ktor를 통한 라우팅, 요청 처리, 파라미터 기초를 학습합니다.의 기능을 이번 프로젝트로 이전해 보겠습니다.

작업 저장소 재사용

작업 저장소는 수정 없이 그대로 재사용할 수 있으므로 먼저 작업해 보겠습니다.

  1. model 패키지 안에 새 TaskRepository.kt 파일을 생성합니다.

  2. TaskRepository.kt 를 열고 아래 코드를 추가합니다:

    kotlin
    package com.example.model
    
    object TaskRepository {
        private val tasks = mutableListOf(
            Task("cleaning", "Clean the house", Priority.Low),
            Task("gardening", "Mow the lawn", Priority.Medium),
            Task("shopping", "Buy the groceries", Priority.High),
            Task("painting", "Paint the fence", Priority.Medium)
        )
    
        fun allTasks(): List<Task> = tasks
    
        fun tasksByPriority(priority: Priority) = tasks.filter {
            it.priority == priority
        }
    
        fun taskByName(name: String) = tasks.find {
            it.name.equals(name, ignoreCase = true)
        }
    
        fun addTask(task: Task) {
            if (taskByName(task.name) != null) {
                throw IllegalStateException("Cannot duplicate task names!")
            }
            tasks.add(task)
        }
    }

GET 요청용 라우트 재사용

저장소를 생성했으므로 이제 GET 요청을 위한 라우트를 구현할 수 있습니다. 작업을 HTML로 변환하는 작업을 더 이상 신경 쓸 필요가 없으므로 이전 코드를 단순화할 수 있습니다:

  1. src/main/kotlin 의 Routing.kt 파일로 이동합니다.

  2. Application.configureRouting() 함수 안의 /tasks 라우트 코드를 다음 구현으로 업데이트합니다:

    kotlin
    package com.example
    
    import com.example.model.Priority
    import com.example.model.TaskRepository
    import io.ktor.http.*
    import io.ktor.server.application.*
    import io.ktor.server.http.content.*
    import io.ktor.server.response.*
    import io.ktor.server.routing.*
    
    fun Application.configureRouting() {
        routing {
            staticResources("static", "static")
    
            //업데이트된 구현
            route("/tasks") {
                get {
                    val tasks = TaskRepository.allTasks()
                    call.respond(tasks)
                }
    
                get("/byName/{taskName}") {
                    val name = call.parameters["taskName"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
    
                    val task = TaskRepository.taskByName(name)
                    if (task == null) {
                        call.respond(HttpStatusCode.NotFound)
                        return@get
                    }
                    call.respond(task)
                }
                get("/byPriority/{priority}") {
                    val priorityAsText = call.parameters["priority"]
                    if (priorityAsText == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    try {
                        val priority = Priority.valueOf(priorityAsText)
                        val tasks = TaskRepository.tasksByPriority(priority)
    
                        if (tasks.isEmpty()) {
                            call.respond(HttpStatusCode.NotFound)
                            return@get
                        }
                        call.respond(tasks)
                    } catch (ex: IllegalArgumentException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
            }
        }
    }

    이제 서버는 다음과 같은 GET 요청에 응답할 수 있습니다:

    • /tasks는 저장소의 모든 작업을 반환합니다.
    • /tasks/byName/{taskName}은 지정된 taskName으로 필터링된 작업을 반환합니다.
    • /tasks/byPriority/{priority}는 지정된 priority로 필터링된 작업을 반환합니다.
  3. IntelliJ IDEA에서 재실행 버튼(IntelliJ IDEA 재실행 아이콘)을 클릭하여 애플리케이션을 다시 시작합니다.

기능 테스트하기

브라우저 사용하기

    브라우저에서 이러한 라우트를 테스트할 수 있습니다. 예를 들어, http://0.0.0.0:8080/tasks/byPriority/Medium으로 이동하여 Medium 우선순위를 가진 모든 작업이 JSON 형식으로 표시되는 것을 확인할 수 있습니다:

    보통 우선순위 작업이 JSON 형식으로 표시된 브라우저 창

    이러한 유형의 요청은 일반적으로 JavaScript에서 발생하므로, 보다 세분화된 테스트를 수행하는 것이 좋습니다. 이를 위해 Postman과 같은 전문 도구를 사용할 수 있습니다.

Postman 사용하기

  1. Postman에서 URL이 http://0.0.0.0:8080/tasks/byPriority/Medium인 새 GET 요청을 생성합니다.

  2. Headers 창에서 Accept 헤더의 값을 application/json으로 설정합니다.

  3. Send 를 클릭하여 요청을 보내고 응답 뷰어에서 응답을 확인합니다.

    Postman에서 보통 우선순위 작업이 JSON 형식으로 표시된 GET 요청

HTTP 요청 파일 사용하기

    IntelliJ IDEA Ultimate에서는 HTTP 요청 파일 내에서 동일한 단계를 수행할 수 있습니다.

  1. 프로젝트 루트 디렉터리에 새 REST Task Manager.http 파일을 생성합니다.

  2. REST Task Manager.http 파일을 열고 다음 GET 요청을 추가합니다:

    http
    GET http://0.0.0.0:8080/tasks/byPriority/Medium
    Accept: application/json
  3. IntelliJ IDEA 내에서 요청을 보내려면 요청 옆의 거터 아이콘(IntelliJ IDEA 거터 아이콘)을 클릭합니다.

  4. 그러면 Services 도구 창에서 열리고 실행됩니다:

    HTTP 파일에서 보통 우선순위 작업이 JSON 형식으로 표시된 GET 요청
라우트를 테스트하는 또 다른 방법으로 Kotlin Notebook 내에서 khttp 라이브러리를 사용할 수도 있습니다.

POST 요청용 라우트 추가

이전 튜토리얼에서는 HTML 폼을 통해 작업을 생성했습니다. 하지만 이제는 RESTful 서비스를 구축하고 있으므로 더 이상 그럴 필요가 없습니다. 대신 많은 번거로운 작업을 대신 처리해 주는 kotlinx.serialization 프레임워크를 활용합니다.

  1. src/main/kotlin 안의 Routing.kt 파일을 엽니다.

  2. Application.configureRouting() 함수에 다음과 같이 새 POST 라우트를 추가합니다:

    kotlin
    //...
    
    fun Application.configureRouting() {
        routing {
            //...
    
            route("/tasks") {
                //...
    
                //다음 새 라우트 추가
                post {
                    try {
                        val task = call.receive<Task>()
                        TaskRepository.addTask(task)
                        call.respond(HttpStatusCode.Created)
                    } catch (ex: IllegalStateException) {
                        call.respond(HttpStatusCode.BadRequest)
                    } catch (ex: SerializationException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
            }
        }
    }

    다음 새 import를 추가합니다:

    kotlin
    //...
    import com.example.model.Task
    import io.ktor.server.request.receive
    import kotlinx.serialization.SerializationException

    POST 요청이 /tasks로 전송되면 kotlinx.serialization 프레임워크를 사용하여 요청 본문을 Task 객체로 변환합니다. 변환에 성공하면 작업이 저장소에 추가됩니다. 역직렬화 프로세스가 실패하면 서버는 SerializationException을 처리하고, 중복된 작업인 경우에는 IllegalStateException을 처리합니다.

  3. 애플리케이션을 다시 시작합니다.

  4. Postman에서 이 기능을 테스트하려면 URL http://0.0.0.0:8080/tasks로 새 POST 요청을 생성합니다.

  5. Body 패널에서 새 작업을 나타내는 다음 JSON 문서를 추가합니다:

    json
    {
        "name": "cooking",
        "description": "Cook the dinner",
        "priority": "High"
    }
    새 작업을 추가하기 위한 Postman의 POST 요청
  6. Send 를 클릭하여 요청을 보냅니다.

  7. http://0.0.0.0:8080/tasks로 GET 요청을 보내 작업이 추가되었는지 확인할 수 있습니다.

  8. IntelliJ IDEA Ultimate 내에서는 HTTP 요청 파일에 다음 내용을 추가하여 동일한 단계를 수행할 수 있습니다:

    http
    ###
    
    POST http://0.0.0.0:8080/tasks
    Content-Type: application/json
    
    {
        "name": "cooking",
        "description": "Cook the dinner",
        "priority": "High"
    }

삭제 지원 추가

서비스에 기본 작업을 추가하는 과정이 거의 완료되었습니다. 이러한 작업은 흔히 CRUD(Create, Read, Update, Delete) 작업으로 요약됩니다. 이제 삭제(Delete) 작업을 구현해 보겠습니다.

  1. TaskRepository.kt 파일의 TaskRepository 객체 내에 이름을 기반으로 작업을 제거하는 다음 메서드를 추가합니다:

    kotlin
    fun removeTask(name: String): Boolean {
        return tasks.removeIf { it.name == name }
    }
  2. Routing.kt 파일을 열고 DELETE 요청을 처리하기 위한 엔드포인트를 routing() 함수에 추가합니다:

    kotlin
    fun Application.configureRouting() {
        //...
    
        routing {
            route("/tasks") {
                //...
                //다음 함수 추가
                delete("/{taskName}") {
                    val name = call.parameters["taskName"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@delete
                    }
    
                    if (TaskRepository.removeTask(name)) {
                        call.respond(HttpStatusCode.NoContent)
                    } else {
                        call.respond(HttpStatusCode.NotFound)
                    }
                }
            }
        }
    }
  3. 애플리케이션을 다시 시작합니다.

  4. HTTP 요청 파일에 다음 DELETE 요청을 추가합니다:

    http
    ###
    
    DELETE http://0.0.0.0:8080/tasks/gardening
  5. IntelliJ IDEA 내에서 DELETE 요청을 보내려면 요청 옆의 거터 아이콘(IntelliJ IDEA 거터 아이콘)을 클릭합니다.

  6. Services 도구 창에서 응답을 확인할 수 있습니다:

    HTTP 요청 파일의 DELETE 요청

Ktor Client로 단위 테스트 작성하기

지금까지는 애플리케이션을 수동으로 테스트했지만 이미 눈치채셨듯이 이 방법은 시간이 많이 걸리고 확장성이 떨어집니다. 대신 내장된 client 객체를 사용하여 JSON을 가져오고 역직렬화하는 JUnit 테스트특별한 테스트 엔진을 사용하여 서버 애플리케이션을 테스트하는 방법을 알아봅니다.를 구현할 수 있습니다.

  1. src/test/kotlin 안의 ServerTest.kt 파일을 엽니다.

  2. ServerTest.kt 파일의 내용을 다음으로 교체합니다:

    kotlin
    package com.example
    
    import com.example.model.Priority
    import com.example.model.Task
    import io.ktor.client.call.*
    import io.ktor.client.plugins.contentnegotiation.*
    import io.ktor.client.request.*
    import io.ktor.http.*
    import io.ktor.serialization.kotlinx.json.*
    import io.ktor.server.testing.*
    import kotlin.test.*
    
    class ApplicationTest {
        @Test
        fun tasksCanBeFoundByPriority() = testApplication {
            configure()
            val client = createClient {
                install(ContentNegotiation) {
                    json()
                }
            }
    
            val response = client.get("/tasks/byPriority/Medium")
            val results = response.body<List<Task>>()
    
            assertEquals(HttpStatusCode.OK, response.status)
    
            val expectedTaskNames = listOf("gardening", "painting")
            val actualTaskNames = results.map(Task::name)
            assertContentEquals(expectedTaskNames, actualTaskNames)
        }
    
        @Test
        fun invalidPriorityProduces400() = testApplication {
            configure()
            val response = client.get("/tasks/byPriority/Invalid")
            assertEquals(HttpStatusCode.BadRequest, response.status)
        }
    
    
        @Test
        fun unusedPriorityProduces404() = testApplication {
            configure()
            val response = client.get("/tasks/byPriority/Vital")
            assertEquals(HttpStatusCode.NotFound, response.status)
        }
    
        @Test
        fun newTasksCanBeAdded() = testApplication {
            configure()
            val client = createClient {
                install(ContentNegotiation) {
                    json()
                }
            }
    
            val task = Task("swimming", "Go to the beach", Priority.Low)
            val response1 = client.post("/tasks") {
                header(
                    HttpHeaders.ContentType,
                    ContentType.Application.Json
                )
    
                setBody(task)
            }
            assertEquals(HttpStatusCode.Created, response1.status)
    
            val response2 = client.get("/tasks")
            assertEquals(HttpStatusCode.OK, response2.status)
    
            val taskNames = response2
                .body<List<Task>>()
                .map { it.name }
    
            assertContains(taskNames, "swimming")
        }
    }

    서버에서 했던 것과 동일한 방식으로 Ktor 클라이언트에도 ContentNegotiation 및 kotlinx.serialization 플러그인을 설치해야 한다는 점에 유의하세요.

  3. build.gradle.kts 파일에 다음 종속성을 추가합니다:

    kotlin
    testImplementation(ktorLibs.client.contentNegotiation)

JsonPath로 단위 테스트 작성하기

Ktor 클라이언트 또는 유사한 라이브러리를 사용하여 서비스를 테스트하는 것은 편리하지만, 품질 보증(QA) 관점에서는 단점이 있습니다. 서버가 JSON을 직접 다루지 않기 때문에 JSON 구조에 대한 가정이 확실한지 확신할 수 없습니다.

예를 들어 다음과 같은 가정들이 있습니다:

  • 실제로는 object가 사용되는데 값이 array에 저장된다고 가정하는 경우.
  • 속성이 실제로는 string인데 number로 저장된다고 가정하는 경우.
  • 멤버가 선언 순서대로 직렬화되지 않는데 선언 순서대로 직렬화된다고 가정하는 경우.

서비스가 여러 클라이언트에 의해 사용될 예정이라면 JSON 구조에 대한 확신을 갖는 것이 중요합니다. 이를 위해 Ktor Client를 사용하여 서버에서 텍스트를 검색한 다음 JSONPath 라이브러리를 사용하여 이 내용을 분석합니다.

  1. gradle/libs.versions.toml 파일을 열고 JSONPath 버전과 라이브러리 별칭을 정의합니다:

    toml
    [versions]
    json-path = "2.9.0"
    [libraries]
    json-path = { module = "com.jayway.jsonpath:json-path", version.ref = "json-path" }
  2. build.gradle.kts 파일의 dependencies 블록에 JSONPath 라이브러리를 추가합니다:

    kotlin
    testImplementation(libs.json.path)
  3. src/test/kotlin 폴더로 이동하여 새 ApplicationJsonPathTest.kt 파일을 생성합니다.

  4. ApplicationJsonPathTest.kt 파일을 열고 다음 내용을 추가합니다:

    kotlin
    package com.example
    
    import com.jayway.jsonpath.DocumentContext
    import com.jayway.jsonpath.JsonPath
    import io.ktor.client.*
    import com.example.model.Priority
    import io.ktor.client.request.*
    import io.ktor.client.statement.*
    import io.ktor.http.*
    import io.ktor.server.testing.*
    import kotlin.test.*
    
    
    class ApplicationJsonPathTest {
        @Test
        fun tasksCanBeFound() = testApplication {
            configure()
            val jsonDoc = client.getAsJsonPath("/tasks")
    
            val result: List<String> = jsonDoc.read("$[*].name")
            assertEquals("cleaning", result[0])
            assertEquals("gardening", result[1])
            assertEquals("shopping", result[2])
        }
    
        @Test
        fun tasksCanBeFoundByPriority() = testApplication {
            configure()
            val priority = Priority.Medium
            val jsonDoc = client.getAsJsonPath("/tasks/byPriority/$priority")
    
            val result: List<String> =
                jsonDoc.read("$[?(@.priority == '$priority')].name")
            assertEquals(2, result.size)
    
            assertEquals("gardening", result[0])
            assertEquals("painting", result[1])
        }
    
        suspend fun HttpClient.getAsJsonPath(url: String): DocumentContext {
            val response = this.get(url) {
                accept(ContentType.Application.Json)
            }
            return JsonPath.parse(response.bodyAsText())
        }
    }

    JsonPath 쿼리는 다음과 같이 동작합니다:

    • $[*].name은 "문서를 배열로 처리하고 각 항목의 name 속성 값을 반환함"을 의미합니다.
    • $[?(@.priority == '$priority')].name은 "배열의 모든 항목 중 지정된 값과 일치하는 priority를 가진 항목의 name 속성 값을 반환함"을 의미합니다.

    이와 같은 쿼리를 사용하여 반환된 JSON에 대한 이해가 맞는지 확인할 수 있습니다. 코드 리팩터링 및 서비스 재배포를 수행할 때 직렬화의 모든 변경 사항이 감지되며, 이는 현재 프레임워크에서 역직렬화 오류를 일으키지 않더라도 파악됩니다. 이를 통해 공개 API를 자신 있게 다시 배포할 수 있습니다.

다음 단계

축하합니다! 이제 작업 관리자 애플리케이션을 위한 RESTful API 서비스 생성을 완료했으며, Ktor Client와 JsonPath를 사용한 단위 테스트의 세부 사항까지 익혔습니다.

다음 튜토리얼Kotlin, Ktor 및 Thymeleaf 템플릿을 사용하여 웹사이트를 구축하는 방법을 알아봅니다.로 이동하여 API 서비스를 재사용하여 웹 애플리케이션을 빌드하는 방법을 알아보세요.