运行 在 ScalaTest 中使用 ScalaFutures 的测试有时会抛出 IllegalStateException
Running tests using ScalaFutures in ScalaTest throws IllegalStateException from time to time
当 运行 使用 scalatest 进行测试时,我有时会收到 IllegalStateException:
The future returned an exception of type:
java.lang.IllegalStateException, with message: Cannot initialize
ExecutionContext; AsyncExecutor already shut down.
我将 ScalaTest 2.2.6 与 Play 框架 2.4 和 Slick 3.1 结合使用。测试如下所示:
class FooDaoImplSpec
extends PlaySpec
with TestConfiguration
with OneAppPerSuite
with ScalaFutures
with IntegrationPatience {
override lazy val app = new GuiceApplicationBuilder()
.loadConfig(testConfig)
.in(Mode.Test)
.bindings(bind[FooDao].to[FooDaoImpl])
.build
"FooDao#findAll" must {
"return a result set with the length of 3" in {
val fooDao = app.injector.instanceOf[FooDao]
val result: Future[Seq[FooModel]] = fooDao.findAll()
whenReady(result) { r =>
r must have length (3)
}
}
}
}
上例中的fooDao
使用Slick查询数据库。也许还值得一提的是 FooDaoImpl
使用 Play 的内部执行上下文 (play.api.libs.concurrent.Execution.Implicits.defaultContext
)。
我真的有点卡在这里。正如我已经提到的,异常是在我的一个测试套件中随机抛出的,但只是偶尔抛出。
有没有其他人遇到过同样的问题?感谢任何帮助。
好的,看来我明白了。我不小心将 parallelExecution
中的测试 运行 设置为 true
。以下 sbt 设置为我解决了这个问题:
parallelExecution in Test := false
fork in Test := true
当 运行 使用 scalatest 进行测试时,我有时会收到 IllegalStateException:
The future returned an exception of type: java.lang.IllegalStateException, with message: Cannot initialize ExecutionContext; AsyncExecutor already shut down.
我将 ScalaTest 2.2.6 与 Play 框架 2.4 和 Slick 3.1 结合使用。测试如下所示:
class FooDaoImplSpec
extends PlaySpec
with TestConfiguration
with OneAppPerSuite
with ScalaFutures
with IntegrationPatience {
override lazy val app = new GuiceApplicationBuilder()
.loadConfig(testConfig)
.in(Mode.Test)
.bindings(bind[FooDao].to[FooDaoImpl])
.build
"FooDao#findAll" must {
"return a result set with the length of 3" in {
val fooDao = app.injector.instanceOf[FooDao]
val result: Future[Seq[FooModel]] = fooDao.findAll()
whenReady(result) { r =>
r must have length (3)
}
}
}
}
上例中的fooDao
使用Slick查询数据库。也许还值得一提的是 FooDaoImpl
使用 Play 的内部执行上下文 (play.api.libs.concurrent.Execution.Implicits.defaultContext
)。
我真的有点卡在这里。正如我已经提到的,异常是在我的一个测试套件中随机抛出的,但只是偶尔抛出。
有没有其他人遇到过同样的问题?感谢任何帮助。
好的,看来我明白了。我不小心将 parallelExecution
中的测试 运行 设置为 true
。以下 sbt 设置为我解决了这个问题:
parallelExecution in Test := false
fork in Test := true