[kotlin] 코틀린 스프링 부트 애플리케이션 테스트 방법

코틀린으로 작성된 스프링 부트 애플리케이션을 효과적으로 테스트하는 방법에 대해 알아보겠습니다.

1. 단위 테스트(Unit Test)

코틀린으로 작성된 스프링 부트 애플리케이션을 단위 테스트하기 위해서는 테스트 기본 도구로서 JUnit을 사용할 수 있습니다.

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT
import org.springframework.boot.test.web.client.TestRestTemplate

@SpringBootTest(webEnvironment = RANDOM_PORT)
class MyControllerTest {

    @Autowired
    lateinit var restTemplate: TestRestTemplate

    @Test
    fun `test example`() {
        val result = restTemplate.getForObject("/example", String::class.java)
        // perform assertions on the result
    }
}

2. 통합 테스트(Integration Test)

스프링 부트 애플리케이션의 통합 테스트는 @SpringBootTest 애노테이션을 사용하여 스프링 애플리케이션 컨텍스트를 로드하여 실행하는 방식으로 수행됩니다.

import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.beans.factory.annotation.Autowired

@SpringBootTest(webEnvironment = RANDOM_PORT)
class MyIntegrationTest {

    @Autowired
    lateinit var restTemplate: TestRestTemplate

    @Test
    fun `test example`() {
        val result = restTemplate.getForObject("/example", String::class.java)
        // perform assertions on the result
    }
}

3. REST API 테스트

REST API를 테스트하기 위해서는 TestRestTemplate를 사용합니다.

import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.web.server.LocalServerPort

@SpringBootTest(webEnvironment = RANDOM_PORT)
class MyRestApiTest {

    @LocalServerPort
    private val port: Int = 0

    @Autowired
    lateinit var restTemplate: TestRestTemplate

    @Test
    fun `test example endpoint`() {
        val result = restTemplate.getForObject("http://localhost:" + port + "/example", String::class.java)
        // perform assertions on the result
    }
}

위의 방법들을 사용하여 코틀린으로 작성된 스프링 부트 애플리케이션을 다양한 시나리오에 대해 효과적으로 테스트할 수 있습니다.

참고 자료:

그럼 테스팅하시고 좋은 결과를 얻기를 바랍니다!