【发布时间】:2016-03-13 14:34:39
【问题描述】:
播放 2.4 应用,使用 dependency injection 服务类。
我发现,当正在测试的服务类具有多个注入依赖项时,Specs2 会阻塞。它失败并显示“找不到类的构造函数...”
$ test-only services.ReportServiceSpec
[error] Can't find a constructor for class services.ReportService
[error] Error: Total 1, Failed 0, Errors 1, Passed 0
[error] Error during tests:
[error] services.ReportServiceSpec
[error] (test:testOnly) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 2 s, completed Dec 8, 2015 5:24:34 PM
生产代码,为了重现这个问题而被剥离到最低限度:
package services
import javax.inject.Inject
class ReportService @Inject()(userService: UserService, supportService: SupportService) {
// ...
}
class UserService {
// ...
}
class SupportService {
// ...
}
测试代码:
package services
import javax.inject.Inject
import org.specs2.mutable.Specification
class ReportServiceSpec @Inject()(service: ReportService) extends Specification {
"ReportService" should {
"Work" in {
1 mustEqual 1
}
}
}
如果我从ReportService 中删除UserService 或SupportService 依赖项,则测试有效。但显然,依赖项存在于生产代码中是有原因的。 问题是,我该如何进行这项测试?
编辑:当尝试在 IntelliJ IDEA 中运行测试时,同样的事情失败了,但有不同的消息:“测试框架意外退出”,“这看起来像一个 specs2 异常......” ;见full output with stacktrace。我按照输出中的说明打开了 Specs2 issue,但我不知道问题出在 Play、Specs2 还是其他地方。
我的库依赖项如下。 (我尝试指定 Specs2 版本 explicitly,但这没有帮助。看起来我需要 specs2 % Test 原样,以便 Play 的测试类(如 WithApplication)工作。)
resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases"
libraryDependencies ++= Seq(
specs2 % Test,
jdbc,
evolutions,
filters,
"com.typesafe.play" %% "anorm" % "2.4.0",
"org.postgresql" % "postgresql" % "9.4-1205-jdbc42"
)
【问题讨论】:
标签: scala playframework dependency-injection specs2 playframework-2.4