2015-09-14 6 views
6

Ich arbeite an einer Play (V. 2.4) -Anwendung mit Guice als DI-Provider. Alles läuft gut, aber ich habe eine Reihe von Funktionstests laufen mit ScalaTestPlus und ich möchte einige Abhängigkeiten zu ersetzen, wenn der Test ausgeführt wird. Die Tests werden geschrieben, indem die Klasse OneServerPerSuite erweitert wird, während sie meine REST-API überprüfen.Wie ändere ich Guice-Bindungen für Funktionstests?

Gibt es eine Möglichkeit, andere Abhängigkeiten während der Tests zu haben?

EDIT: Beispielcode:

Beispiel Controller:

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

Und dependecy Definition in Modul:

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

Meine Tests sind wie folgt aus:

class ApiTest extends PlaySpec with OneServerPerSuite { 

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

Ich möchte ProdUserService mit einer anderen Implementierung ersetzt haben, aber nur in Tests.

+0

Haben Sie Codebeispiel? – Kmeixner

+1

Ich habe die Frage mit Beispielcode aktualisiert. – walak

Antwort

1

Dies sollte es tun:

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 
     } 
    } 
}