2015-09-14 13 views
6

Sto lavorando a un'applicazione Play (v. 2.4) con Guice come provider DI. Tutto funziona bene, tuttavia ho una serie di test funzionali in esecuzione con ScalaTestPlus e vorrei sostituire alcune dipendenze quando il test è in esecuzione. I test vengono scritti estendendo la classe OneServerPerSuite mentre controllano la mia API REST.Come cambio i collegamenti Guice per i test funzionali?

C'è un modo per avere altre dipendenze durante i test?

EDIT: Codice di esempio:

regolatore del campione:

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

E dependecy definizione nel modulo:

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

miei test sono come questo:

class ApiTest extends PlaySpec with OneServerPerSuite { 

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

Mi piacerebbe avere ProdUserService sostituito con altra implementazione ma solo nei test.

+0

Avete qualche codice di esempio? – Kmeixner

+1

Ho aggiornato la domanda con un codice di esempio. – walak

risposta

1

Questo dovrebbe farlo:

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