如何以编程方式启动 ktor-server 以进行集成测试
Posted
技术标签:
【中文标题】如何以编程方式启动 ktor-server 以进行集成测试【英文标题】:How can I start ktor-server programmatically for Integration-Tests 【发布时间】:2020-07-29 10:35:11 【问题描述】:KTor 与单元测试配合得很好,但是如何启动我的 ktor 服务器进行集成测试?
这是我的测试的样子:
@ExperimentalCoroutinesApi
class HttpClientTest
private val logger = LoggerFactory.getLogger(HttpClientTest::class.java.name)
companion object
@BeforeClass
@JvmStatic
fun setup()
// ?????
@AfterClass
@JvmStatic
fun teardown()
// ????
@Test
fun testMitDefaultHttpClient()
val httpget = HttpGet("http://0.0.0.0:8080/json/gson")
httpget.setHeader("Accept", "application/json")
httpget.setHeader("Content-Type", "application/json")
val httpclient: HttpClient = HttpClients.createDefault()
val response = httpclient.execute(httpget)
Assert.assertEquals(200, response.statusLine.statusCode.toLong())
val responseString = EntityUtils.toString(response.entity)
logger.info(responseString)
【问题讨论】:
【参考方案1】:好的 - 找到了解决方案:
package at.mikemitterer.catshostel.routes
import at.mikemitterer.catshostel.WsClientApp.main
import at.mikemitterer.catshostel.main
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.applicationEngineEnvironment
import io.ktor.server.engine.connector
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.netty.NettyApplicationEngine
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.junit.*
import org.koin.test.KoinTest
import org.slf4j.LoggerFactory
@ExperimentalCoroutinesApi
class HttpClientTest : KoinTest
private val logger = LoggerFactory.getLogger(HttpClientTest::class.java.name)
companion object
lateinit var server: NettyApplicationEngine
@BeforeClass
@JvmStatic
fun setup()
val env = applicationEngineEnvironment
module
main(true)
// Public API
connector
host = "0.0.0.0"
port = 8080
server = embeddedServer(Netty, env).start(false)
@AfterClass
@JvmStatic
fun teardown()
// clean up after this class, leave nothing dirty behind
server.stop(1000, 10000)
@Test
fun testMitDefaultHttpClient()
val httpget = HttpGet("http://0.0.0.0:8080/json/gson")
httpget.setHeader("Accept", "application/json")
httpget.setHeader("Content-Type", "application/json")
val httpclient: HttpClient = HttpClients.createDefault()
val response = httpclient.execute(httpget)
Assert.assertEquals(200, response.statusLine.statusCode.toLong())
val responseString = EntityUtils.toString(response.entity)
logger.info(responseString)
【讨论】:
以上是关于如何以编程方式启动 ktor-server 以进行集成测试的主要内容,如果未能解决你的问题,请参考以下文章
C#:如何以编程方式检查 Web 服务是不是已启动并正在运行?