由于我使用依赖注入(inject),Scala play 2.5 测试未运行

标签 scala playframework sbt guice scalatest

我将我的单元测试从:

class UserSpec extends PlaySpec with OneAppPerTest with BeforeAndAfter with AsyncAssertions
{

致:

class UserSpec @Inject() (implicit exec: ExecutionContext, db: DBConnectionPool)
  extends PlaySpec with OneAppPerTest with BeforeAndAfter with AsyncAssertions
{

第一个版本一切正常,但现在,当我启动测试时,我得到以下结果:

[info] No tests were executed.
[success] Total time: 4 s, completed Dec 5, 2016 8:35:24 PM

请注意,我真的不希望我的测试使用在测试和生产中注入(inject)的相同依赖项来运行。谢谢!

编辑

Code available on github

最佳答案

使用 scalatest 编写 Play 测试时,不使用构造函数注入(inject)。 相反,在混合服务器或应用特征(例如 OneAppPerTest)时,您可以直接在 app.injector 字段中访问注入(inject)器。这样,如果您需要 DI 图中的任何内容,您可以将字段注入(inject)到您的测试套件中:

val example = app.injector.instanceOf[Example]

所以你的初始代码是正确的方法,与直接使用注入(inject)器混合。它可能看起来类似于:

class UserSpec extends PlaySpec with OneAppPerSuite 
               with BeforeAndAfter with AsyncAssertions {

  implicit val exec : ExecutionContext = app.injector.instanceOf[ExecutionContext]
  val db : DBConnectionPool = app.injector.instanceOf[DBConnectionPool]

  // ...

}

就自定义测试的 DI 绑定(bind)而言,您可以通过 GuiceApplicationBuilder 自定义应用实例来覆盖它们,请参阅 Creating Application Instances for TestingTesting with Guice

关于由于我使用依赖注入(inject),Scala play 2.5 测试未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982230/

相关文章:

scala - Maven setting.xml 等效于 sbt

java - Maven 组装插件合并策略

Scala 构造函数重载?

javascript - Play 框架如何处理来自 WebSocket 的 CloseEvent?

azure - 使用 Play 框架时通过 Application Insights 启用 Web 请求日志记录

playframework - Play 莫名报告类 "already defined"

scala - 当只有插件的源可用时,如何在 sbt 项目中使用插件?

scala - 使用 SBT 为不同的库版本构建

scala - 在“sbt运行”时抛出sbt.TrapExitSecurityException

scala - 参数表达式的类型与形参类型不兼容,您可能希望研究通配符类型,例如 `_ <: Any` 。 (SLS 3.2.10)