Ktor - 单元测试抛出 404

Pat*_*kós 3 junit unit-testing httprequest kotlin ktor

我在 Ktor 中有一个简单的程序。它运行完美,但是当我运行单元测试类时,它只会抛出此错误:“expected:<200 OK> but was:<404 Not Found>”

这是我的单元测试代码:

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

@Test
fun testStart() = testApplication {
    val response = client.post("/start")
    assertEquals(HttpStatusCode.OK, response.status)
}
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Application.kt:

const val enableHTTPS = false
const val portHTTP = 80
const val portHTTPS = 7001


lateinit var environment: ApplicationEngineEnvironment
fun main() {
    initEnvironment()

    embeddedServer(Netty, environment = environment).start(wait = true)
}

Run Code Online (Sandbox Code Playgroud)

我的路由文件是:

fun Application.configureRouting() {
    routing {
        get {
            call.respond(ApiDetails())
        }

        post("/start") {
            call.response.status(HttpStatusCode.OK)
        }

        post("/move") {
            val gameDetails: GameDetails = call.receive()
            val move = BasicStrategy().move(gameDetails, application)

            call.respond(move)
        }

        post("/end") {
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

Moh*_*wia 5

要测试应用程序,应将其模块加载到testApplication. 加载模块取决于创建服务器的testApplication方式:使用配置文件或使用函数的代码。application.confembeddedServer

application.conf如果资源文件夹中有该文件,testApplication则会自动加载配置文件中指定的所有模块和属性。

您可以通过自定义测试环境来禁用加载模块。

如果使用embeddedServer,您可以使用应用程序功能手动将模块添加到测试应用程序:

fun testModule1() = testApplication {
    application {
        module1()
        module2()
    }
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

class ApplicationTest {
@Test
fun testRoot() = testApplication {
    application {
        configureRouting()
    }
    environment {
        config = MapApplicationConfig(
            "ktor.deployment.port" to "80",
            "ktor.deployment.sslPort" to "7001"
        )
    }
    val response = client.get("/")
    assertEquals(HttpStatusCode.OK, response.status)
}

@Test
fun testStart() = testApplication {
    application {
        configureRouting()
    }
    environment {
        config = MapApplicationConfig(
            "ktor.deployment.port" to "80",
            "ktor.deployment.sslPort" to "7001"
        )
    }
    val response = client.post("/start")
    assertEquals(HttpStatusCode.OK, response.status)
}
Run Code Online (Sandbox Code Playgroud)

}