该文档讨论了依赖注入,但并没有真正展示它是如何完成的. 文档也没有完成,并有一堆占位符: http://ktor.io/getting-started.html 我尝试以接受参数(这是我的依赖)的方式创建我的main函数,但是
文档也没有完成,并有一堆占位符:
http://ktor.io/getting-started.html
我尝试以接受参数(这是我的依赖)的方式创建我的main函数,但是当我调用withTestApplication时,在测试端失败了.
我查看了应用程序代码,发现Application接受了一个配置对象,但我不知道如何更改该配置对象以在其中注入一些依赖项.
package org.jetbrains.ktor.application
/**
* Represents configured and running web application, capable of handling requests
*/
class Application(val environment: ApplicationEnvironment) : ApplicationCallPipeline() {
/**
* Called by host when [Application] is terminated
*/
fun dispose() {
uninstallAllFeatures()
}
}
/**
* Convenience property to access log from application
*/
val Application.log get() = environment.log
在使用withTestApplication的测试代码中,我有类似于下面的内容:
@Test internal fun myTest() = withTestApplication (Application::myMain)
如果我用参数调用myMain(我需要模拟和注入的参数),上面的withTestApplication将会失败.
更新:
问题是在我的请求处理中,我使用连接到外部其他Web服务的依赖类并执行一些请求,我需要一种方法能够注入这个,所以在我的测试中我可以存根/模拟它并更改它基于我的测试用例的行为.
Ktor没有内置的依赖注入机制.如果您需要使用DI,则需要使用您喜欢的任何框架,例如Guice.它看起来像这样:fun Application.module() {
Guice.createInjector(MainModule(this))
}
// Main module, binds application and routes
class MainModule(private val application: Application) : AbstractModule() {
override fun configure() {
bind(Application::class.java).toInstance(application)
... other bindings ...
}
}
这样您就可以将应用程序组合委托给Guice并将其构建为任何其他应用程序.例如.你可能会组成你的应用程序的不同部分,如下所示:
class Hello @Inject constructor(application: Application) {
init {
application.routing {
get("/") {
call.respondText("Hello")
}
}
}
}
然后将其绑定在主模块中:
bind(Hello::class.java).asEagerSingleton()
需要asEagerSingleton才能让Guice热切地创建它,因为没有其他服务可以查询它.
