scala - 在规范之前和之后执行代码

标签 scala testing specs2

我有几个案例的简单说明:

class MySpec extends Specification {

  "Something" should {

    "case 1" in {
      ...
    }

    "case 2" in {
      ...
    }
  }
}

现在我需要启动应用程序,运行所有案例,然后关闭应用程序。启动/停止应用程序非常耗时,我不希望它在每种情况下都发生。

如何在案例开始之前和所有案例结束之后运行代码?

最佳答案

我根据 cmbaxter 的回答提出了以下解决方案。

import org.specs2.specification.Step

trait BeforeAllAfterAll extends Specification {
  // see http://bit.ly/11I9kFM (specs2 User Guide)
  override def map(fragments: =>Fragments) = 
    Step(beforeAll) ^ fragments ^ Step(afterAll)

  protected def beforeAll()
  protected def afterAll()
}

然后在Specification中混合BeforeAllAfterAll并实现beforeAllafterAll方法:

class MySpec extends Specification with BeforeAllAfterAll {

  def beforeAll() {
    println("Doing setup work...")
  }

  def afterAll() {
    println("Doing shutdown work...")
  }

  "Something" should {

    "case 1" in {
      ...
    }

    "case 2" in {
      ...
    }
  }
}

最后,提取初始化以在规范之间共享:

trait InApplication extends BeforeAllAfterAll {
  def beforeAll() {
    println("Doing setup work...")
  }

  def afterAll() {
    println("Doing shutdown work...")
  }
}

class MySpec extends Specification with InApplication {

  "Something" should {

    "case 1" in {
      ...
    }

    "case 2" in {
      ...
    }
  }
}

关于scala - 在规范之前和之后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16936811/

相关文章:

javascript - document.write 在 html 中不起作用

scala - 是否有等效的 Java Sound API?

java.lang.Boolean 到 scala.Boolean 的问题

sql - 对 SQL Server 执行计划进行基准测试以进行自动化测试?

javascript - Jest --runTestsByPath 两个或多个不同的路径

unit-testing - EasyMock 和 Mockito 的区别

Scala 任一模式匹配

scala - 为什么这个 specs2 测试使用 Mockito 通过?

scala - Specs2 + JUnit + ScalaTest 初始化错误测试类无法转换为 org.scalatest.Suite