在我的 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/