scala - 如果使用注入(inject),则 PlaySpec 测试类未被拾取

标签 scala dependency-injection playframework scalatest

在我的 Play 2.6.x 应用程序中,我正在使用 PlaySpec 进行测试。现在我想注入(inject)一些要在测试代码中使用的对象。

class AuthControllerTest @Inject()(userRepository: UserRepository)
  extends PlaySpec with GuiceOneAppPerSuite with Injecting {

  "Foo bar" should {
    "do xyz" in {
      // do something with userRepository
    }
  }
}

但是,此类永远不会被选中进行测试,例如在运行 sbt test 时。

一个简单的解决方法是从当前的 Play 实例中手动获取注入(inject)器,但是 Play.current 已被弃用并且通常感觉很糟糕:

class AuthControllerTest
  extends PlaySpec with GuiceOneAppPerSuite with Injecting {

  "Foo bar" should {
    "do xyz" in {
      val userRepository = Play.current.injector.instanceOf[UserRepository]
      // do something with userRepository
    }
  }
}

为什么前面的例子不起作用?是否有比后一个示例更简洁的方法?

最佳答案

Play Framework 不会像第一个示例那样对测试进行依赖注入(inject)。在第二个中,您不需要 Play.current,因为 GuiceOneAppPerSuite 为您提供了一个应用程序 (app)。所以你可以这样做:

val userRepository = app.injector.instanceOf[UserRepository].

并且通过使用Injecting,您可以进一步简化它,例如:

val userRepository = inject[UserRepository]

并且来自 official docs :

If all or most tests in your test class need an Application, and they can all share the same instance of Application, mix in trait GuiceOneAppPerSuite with the GuiceFakeApplicationFactory trait. You can access the Application from the app field.

还有一个关于Injecting的页面在官方文档中。

关于scala - 如果使用注入(inject),则 PlaySpec 测试类未被拾取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443586/

相关文章:

scala - 如何覆盖 Scala 中的预定义函数?

c# - 具有基于数据库值的动态连接字符串的存储库模式

scala - scala匹配器中的多源提取

c# - 什么时候将 RegistrationBuilder 传递给 Catalog?

c# - Func<Owned<T>> 与 Func<T> 依赖关系

playframework - 在本地部署 Play 应用程序

ssl - 如何在 Play 2 框架中使用 SSL?

java - 更改 Java 项目的数据库类型?

scala - Play WS (2.2.1) : post/put large request

Scala:关于实践 session 的想法的建议