在scalatest中尝试使用beforeAll时,没有启动的应用程序
在我的测试课上,我想在所有测试开始之前做一些事情,所以我做了如下事情:在scalatest中尝试使用beforeAll时,没有启动的应用程序,scala,scalatest,scalacheck,Scala,Scalatest,Scalacheck,在我的测试课上,我想在所有测试开始之前做一些事情,所以我做了如下事情: class ApplicationSpec extends FreeSpec with OneServerPerSuite with BeforeAndAfterAll { override protected def beforeAll(): Unit = { doSomething() } "Application Test" - { "first test" in { ...
class ApplicationSpec extends FreeSpec with OneServerPerSuite with BeforeAndAfterAll {
override protected def beforeAll(): Unit = {
doSomething()
}
"Application Test" - {
"first test" in {
...
}
}
}
但我有一个错误:
调用嵌套套件上的运行时遇到异常-存在
没有启动的应用程序java.lang.RuntimeException:没有启动的应用程序
只有在测试中尝试使用doSomething()时,它才会起作用
我怎样才能解决这个问题
谢谢 我假设
doSomething()
执行一些依赖于应用程序状态的操作
试试这个:
class ApplicationSpec extends FreeSpec with BeforeAndAfterAll with OneServerPerSuite{
override protected def beforeAll(): Unit = {
doSomething()
}
"Application Test" - {
"first test" in {
...
}
}
}
问题是您可能以错误的顺序进行了混合线性化
。
通过mixin
OneSerPerSuite before and afterall,调用super.run()
的顺序颠倒,导致在应用程序启动之前调用beforeAll()
根据两个项目的git回购协议:
//BeforeAndAfterAll
abstract override def run(testName: Option[String], args: Args): Status = {
if (!args.runTestInNewInstance && (expectedTestCount(args.filter) > 0 || invokeBeforeAllAndAfterAllEvenIfNoTestsAreExpected))
beforeAll()
val (runStatus, thrownException) =
try {
(super.run(testName, args), None)
}
catch {
case e: Exception => (FailedStatus, Some(e))
}
...
}
//OneServerPerSuite
abstract override def run(testName: Option[String], args: Args): Status = {
val testServer = TestServer(port, app)
testServer.start()
try {
val newConfigMap = args.configMap + ("org.scalatestplus.play.app" -> app) + ("org.scalatestplus.play.port" -> port)
val newArgs = args.copy(configMap = newConfigMap)
val status = super.run(testName, newArgs)
status.whenCompleted { _ => testServer.stop() }
status
} catch { // In case the suite aborts, ensure the server is stopped
case ex: Throwable =>
testServer.stop()
throw ex
}
}
因此,通过将
OneServerPerSuite
特性放在最后,它将首先初始化应用程序
,然后调用super.run()
,它将调用run
方法,该方法将在before和afterall
中执行beforeAll()
,然后调用super.run()FreeSpec
的
将执行测试。您能试用我的解决方案吗?是的,伙计,刚刚查看了它,它解决了问题,您的解释很好,谢谢@苏梅萨马