scala - 何时在具有 BeforeAndAfter 特性的 ScalaTest 类中调用 before() 和 after()

标签 scala scalatest

考虑以下用于 BeforeAndAfterBeforeAndAfterAll 的最小可行自包含测试用例:

import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuite}

class BeforeAndAfterTestTest extends FunSuite with BeforeAndAfter with BeforeAndAfterAll {

  override protected def beforeAll(): Unit = println("beforeAll")

  override protected def afterAll(): Unit = println("afterAll")

  override protected def before(fun: => Any)(implicit pos: Position): Unit = {
    println("before")
  }

  override protected def after(fun: => Any)(implicit pos: Position): Unit = {
    println("after")
  }

  test("hello1") { println("hello1") }

  test("hello2") { println("hello2") }
}

通过 scalatest 运行的结果是:

enter image description here

所以:

  • before/afterAll do 执行
  • 之前/之后

调用 beforeafter 方法需要什么?

最佳答案

您应该调用之前之后,而不是覆盖它们:

import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuite}

class BeforeAndAfterTestTest extends FunSuite with BeforeAndAfter with BeforeAndAfterAll {

  override protected def beforeAll(): Unit = println("beforeAll")

  override protected def afterAll(): Unit = println("afterAll")

  before {
    println("before")
  }

  after {
    println("after")
  }

  test("hello1") { println("hello1") }

  test("hello2") { println("hello2") }
}

参见文档 here

如果你想要可覆盖的方法,你应该使用BeforeAndAfterEach,而不是BeforeAndAfter (doc)

关于scala - 何时在具有 BeforeAndAfter 特性的 ScalaTest 类中调用 before() 和 after(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753284/

相关文章:

arrays - 在数组或Scala Spark中的其他任何集合中迭代RDD和存储的值

scala - 如何将共享测试与需要清理的装置结合起来?

scala - 确保 ScalaTest 不并行运行

scala - scala 中的递归排序与尾递归

java - 如何使用java api更新elasticsearch中的嵌套字段值

scala - 如何在scala spark中添加指定位数的前导零填充?

scala - Spark-rdd 操作数据

Scalatest:如何检查集合是否包含满足特定条件的元素

ScalaTest AsyncFunSuiteLike 多个断言

scala - 如何在 ScalaTest/SBT 中按顺序运行测试套件?