使用多个模块在 ktor 中进行测试

Testing in ktor with multiple modules

我正在玩一个小型 ktor webapp,我想在其中将功能拆分为多个模块。 我有一个根模块,我在其中安装了我想在整个应用程序中使用的功能

fun Application.rootModule(testing: Boolean = false) {
    install(ContentNegotiation) {
        gson {
        }
    }
....

和一个我在其中实现域功能的域模块

fun Application.bookModule() {

    routing {
        get("/books/{id}") {
          ....
        }
    }
}

现在我想对此功能进行测试

class BookControllerTests: StringSpec({

    "get should return correct book"{
        withTestApplication({bookModule()}) {
            val testCall: TestApplicationCall = handleRequest(method = HttpMethod.Get, uri = "/books/42") {
            }
            testCall.response.status() shouldBe HttpStatusCode.OK
        }
    }

})

如果我 运行 这样,我会收到错误消息 Response pipeline couldn't transform 'class org.codeshards.buecherkiste.book.domain.Book' to the OutgoingContent - 因此内容协商不起作用。这是有道理的,因为它安装在此处未调用的根模块中。我通过将根模块和域模块包装在沿着我的测试用例实现的测试模块中解决了这个问题:

fun Application.bookModuleTest() {
    rootModule()
    bookModule()
}

现在这似乎奏效了。

由于我是 ktor 和 kotest 的菜鸟,所以我想征求有关此解决方案的反馈。这是做我想做的事情的正确方法,还是我让自己陷入困境?有更好的解决方案吗?

是的,这是测试应用程序的正确方法,因为模块不相互依赖并且通过配置绑定。另外,除了为 Application 添加一个扩展方法之外,您还可以引入以下辅助函数来进行测试:

fun <T> testApp(test: TestApplicationEngine.() -> T): T {
    return withTestApplication(
        {
            rootModule()
            bookModule()
        }, 
        test
    )
}