2017-09-12 18 views
4

ドキュメントでは依存性注入について説明していますが、実際にどのように処理されているかは示されていません。ktorアプリケーションに依存関係を注入する方法

ドキュメントも同様に完了し、プレースホルダの束を持っていません。 http://ktor.io/getting-started.html

私はそれが(私の依存関係である)パラメータを受け入れるような方法で私の主な機能を作成しようとしましたが、それがテストに失敗しました私がwithTestApplicationと呼ぶときは、 私はアプリケーションコードを調べ、アプリケーションが構成オブジェクトを受け入れるのを見ましたが、その構成オブジェクトを変更して内部にいくつかの依存関係を注入する方法がわかりません。 withTestApplicationを使用して、テストコードでは

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 

私は以下のようなものがあります(私はモックと注入するために必要なパラメータ)

@Test 
internal fun myTest() = withTestApplication (Application::myMain) 

私はパラメータでmyMainを呼び出す場合は、上記のwithTestApplicationは失敗するだろうし

更新:

IS私のリクエスト処理では、外部の他のWebサービスに接続する依存クラスを使用しています。リクエストをいくつか行います。これを私のテストで注入できる方法が必要です。私のテストケースに基づいています。

答えて

4

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のは熱心にそれを作成するように、他のサービスが照会していないであろうから必要とされていますそれ。

+1

私のケースでは、他のサービスとやりとりするクラスの依存関係があります。どうすればそのテストを書くことができますか?(私がテストを書くときには、依存関係を模倣し、本物) –

関連する問題