使用Ktor构建并发微服务:从测试到数据库交互
1. 服务测试
首先,我们要为服务编写测试。在 src/test/kotlin
目录下创建一个名为 ServerTest.kt
的新文件。接着,添加新的依赖:
dependencies {
...
testImplementation("io.ktor:ktor-server-tests:$ktorVersion")
}
然后,在 ServerTest.kt
文件中添加以下内容:
internal class ServerTest {
@Test
fun testStatus() {
withTestApplication {
val response = handleRequest(HttpMethod.Get, "/status").response
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("""{"status": "OK"}""", response.content)
}
}
}
在Kotlin中,测试被分组到类中,每个测试是类中的一个方法,用 @Test
注解标记。在测试方法中,我