junit 如何在Ktor中进行测试时只启动一次应用程序,而不是每次测试启动一次?

yv5phkfx  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(274)

我一直在尝试为我的Ktor应用程序编写一些测试,并按照以下文档进行操作:
https://ktor.io/docs/testing.html#end-to-end
...并使用如下测试设置:

import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.testing.*
import kotlin.test.*

class ApplicationTest {
    @Test
    fun testRoot() = testApplication {
        val response = client.get("/")
        assertEquals(HttpStatusCode.OK, response.status)
        assertEquals("Hello, world!", response.bodyAsText())
    }
}

问题是,当在每个测试中使用testApplication时,当我有大约220个应该运行的测试时,测试崩溃,因为我的应用程序每次 Boot 都要读取一个json文件-导致“打开的文件太多”错误。
我想做的是运行应用程序 * 一次 *,然后将所有HTTP请求发送到应用程序的这个示例,然后关闭应用程序。
而上面发生的情况是,对于200多个测试中的每一个测试,应用程序都被引导和关闭,从而导致内存错误。
如何仅运行一次应用程序?

p4rjhz4m

p4rjhz4m1#

解决了!
我们可以在一个beforeAll函数中启动应用程序,而不是在每个测试中都启动它。下面是一个例子:

import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import io.ktor.test.dispatcher.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test

class MyApiTest {
    lateinit var JSON: Json

    @Test
    fun `Test some endpoint`() = testSuspend {
        testApp.client.get("/something").apply {
            val actual = JSON.decodeFromString<SomeType>(bodyAsText())

            assertEquals(expected, actual)
        }
    }

    companion object {
        lateinit var testApp: TestApplication

        @JvmStatic
        @BeforeAll
        fun setup()  {
            testApp = TestApplication {  }          
        }

        @JvmStatic
        @AfterAll
        fun teardown() {
            testApp.stop()
        }
    }
}

相关问题