手动依赖注入应用程序测试Play 2.5.x.

时间:2016-10-13 10:23:16

标签: scala testing dependency-injection scalatest playframework-2.5

我有手动依赖注入的项目。我可以使用标准Play测试套件测试我的应用程序吗?

play.application.loader =" AppLoader将"

    class AppLoader extends ApplicationLoader  {
  override def load(context: Context): Application = {
    LoggerConfigurator(context.environment.classLoader).foreach(_.configure(context.environment))
    new AppComponents(context).application
  }
}
}

class AppComponents(context: Context) extends BuiltInComponentsFromContext(context) with EhCacheComponents with EvolutionsComponents with DBComponents with HikariCPComponents{

  lazy val applicationController = new controllers.Application(defaultCacheApi, dbApi.database("default"))
  lazy val usersController = new controllers.Users(defaultCacheApi)
  lazy val assets = new controllers.Assets(httpErrorHandler)

  //applicationEvolutions

  // Routes is a generated class
  override def router: Router = new Routes(httpErrorHandler, applicationController, usersController, assets)

现在测试非常简单

class ApplicationTest extends PlaySpec with OneAppPerTest {

 "Application" must {

"send 404 on a bad request" in {
  route(FakeRequest(GET, "/boum")) mustBe None
}
}
}

测试结束时出现错误:

Could not find a suitable constructor in controllers.Application. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument 

我认为我需要以某种方式使用我的AppLoader而不是在ApplicationTest类中使用Guice mechanisam,因为Application controller具有dependacy(cacheApi,dbApi ...)

route方法可以将应用程序作为参数但是如何获取上下文以手动实例化AppLoader类?作为Scala建议的新手是最受欢迎的。

1 个答案:

答案 0 :(得分:0)

这个例子回答了我的所有问题:

https://github.com/playframework/play-scala-compile-di-with-tests

使用术语编译时依赖注入会产生更多结果,然后手动依赖注入。