2015-09-14 13 views
6

私はDIプロバイダとしてGuiceのPlay(v。2.4)アプリケーションに取り組んでいます。すべて正常に動作しますが、ScalaTestPlusで機能テストを実行しています。テストが実行されているときに依存関係を置き換えたいと思っています。テストは、OneServerPerSuiteクラスを拡張して、自分のREST APIをチェックするように書かれています。Guiceバインディングを機能テスト用に変更するにはどうすればよいですか?

テスト中に他の依存関係を持つ方法はありますか?

EDIT:サンプルコード:

サンプルコントローラ:モジュール内

class UserController @Inject()(userService: UserService) extends AbstractController { ... } 

そしてdependecy定義:

class ApiTest extends PlaySpec with OneServerPerSuite { 

    "User API should" must { 
     "get User's data" in { 
      (...) //calling to an endpoint and verifying response 
     } 
    } 
} 

bind(classOf[UserService]) to (classOf[ProdUserService]) 

私のテストは、このようなものです

ProdUserServiceを他の実装に置き換えてテストします。

+0

あなたは任意のサンプルコードをお持ちですか? – Kmeixner

+1

質問をサンプルコードで更新しました。 – walak

答えて

1

これはそれを行う必要があります。

import play.api.test._ 
import play.api.test.Helpers._ 
import play.api.inject.bind 
import play.api.Application 
import play.api.inject.guice.GuiceApplicationBuilder 
import database.AccountDAO 
import play.api.Configuration 
import play.api.Mode 

class ApiTest extends PlaySpec with OneServerPerSuite { 

def app = new GuiceApplicationBuilder() // you create your app 
     .configure(
      Configuration.from(
      Map(// a custom configuration for your tests only 
       "slick.dbs.default.driver" -> "slick.driver.H2Driver$", 
       "slick.dbs.default.db.driver" -> "org.h2.Driver", 
       "slick.dbs.default.db.connectionPool" -> "disabled", 
       "slick.dbs.default.db.keepAliveConnection" -> "true", 
       "slick.dbs.default.db.url" -> "jdbc:h2:mem:test", 
       "slick.dbs.default.db.user" -> "sa", 
       "slick.dbs.default.db.password" -> ""))) 
     .bindings(bind[UserService].to[UserServiceImpl]) // here you can define your bindings for an actual implementation (note the use of square brackets) 
     .in(Mode.Test) 
     .build() 


    "User API should" must { 
     "get User's data" in new WithApplication(app) { 
      // if you want to get the controller with everything injected 
      val app2controller = Application.instanceCache[controllers.UserController] 
      val userController = app2controller(app) // with this you get the controller with the service injected 

      (...) //calling to an endpoint and verifying response 
     } 
    } 
} 
関連する問題