【问题标题】:There is no started application when trying to use beforeAll in scalatest尝试在 scalatest 中使用 beforeAll 时没有启动应用程序
【发布时间】:2017-09-25 11:42:57
【问题描述】:

在我的测试课中,我想在所有测试开始之前做一些事情,所以我做了这样的事情:

class ApplicationSpec extends FreeSpec with OneServerPerSuite with BeforeAndAfterAll {

  override protected def beforeAll(): Unit = {
    doSomething()
  }

  "Application Test" - {
    "first test" in {
      ...
    }
  }

}

但我得到一个错误:

在嵌套套件上调用 run 时遇到异常 - 有 没有启动的应用程序 java.lang.RuntimeException: 没有启动的应用程序

只有当我尝试在测试中使用 doSomething() 时它才有效...

我该如何解决这个问题?

谢谢!

【问题讨论】:

  • 您能试用我的解决方案吗?
  • 是的,伙计,刚刚审查了它,它解决了问题,你的解释很好,谢谢! @SumeetSharma

标签: scala scalatest scalacheck


【解决方案1】:

我假设doSomething() 执行一些依赖于应用程序状态的操作。

试试这个:

class ApplicationSpec extends FreeSpec with BeforeAndAfterAll with OneServerPerSuite{

  override protected def beforeAll(): Unit = {
    doSomething()
  }

  "Application Test" - {
    "first test" in {
      ...
    }
  }

}

问题是你可能是mixin linearization in wrong ordermixinOneSerPerSuite 在 BeforeAndAfterAll 之前,super.run() 的调用顺序颠倒过来,导致 beforeAll() 在 Application 启动之前被调用。

来自两个项目的git repo:

 //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 trait 放在最后,它将first initialize the application,然后调用super.run(),这将调用BeforeAndAfterAll 内部的run 方法,该方法将执行beforeAll(),然后调用super.run()FreeSpec 将执行测试。

【讨论】:

    猜你喜欢
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 2017-06-20
    • 1970-01-01
    相关资源
    最近更新 更多