我有一个简单的你好世界Ktor app:
fun Application.testMe() {
intercept(ApplicationCallPipeline.Call) {
if (call.request.uri == "/")
call.respondText("Hello")
}
}
使用JUnit测试类,我可以为它编写测试,如文档中所示;如下:
class ApplicationTest {
@Test fun testRequest() = withTestApplication(Application::testMe) {
with(handleRequest(HttpMethod.Get, "/")) {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("Hello", response.content)
}
with(handleRequest(HttpMethod.Get, "/index.html")) {
assertFalse(requestHandled)
}
}
}
但是,我想在没有JUnit帮助的情况下在Spek或KotlinTest中进行单元测试,类似于我在ScalaTest / Play中的方式;以更具声明性的方式:
/
)。 问题是我可以在KotlinTest或Spek中以更具声明性的方式编写上述测试吗?
答案 0 :(得分:3)
首先,请关注spek setup guide with JUnit 5
然后您可以简单地声明您的规范,如下所示
object HelloApplicationSpec: Spek({
given("an application") {
val engine = TestApplicationEngine(createTestEnvironment())
engine.start(wait = false) // for now we can't eliminate it
engine.application.main() // our main module function
with(engine) {
on("index") {
it("should return Hello World") {
handleRequest(HttpMethod.Get, "/").let { call ->
assertEquals("Hello, World!", call.response.content)
}
}
it("should return 404 on POST") {
handleRequest(HttpMethod.Post, "/", {
body = "HTTP post body"
}).let { call ->
assertFalse(call.requestHandled)
}
}
}
}
}
})
这是我的build.gradle(简化)
buildscript {
dependencies {
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
}
repositories {
jcenter()
}
}
repositories {
jcenter()
maven { url "http://dl.bintray.com/jetbrains/spek" }
}
apply plugin: 'org.junit.platform.gradle.plugin'
junitPlatform {
filters {
engines {
include 'spek'
}
}
}
dependencies {
testCompile 'org.jetbrains.spek:spek-api:1.1.5'
testRuntime 'org.jetbrains.spek:spek-junit-platform-engine:1.1.5'
testCompile "io.ktor:ktor-server-test-host:$ktor_version"
}