ScalaTest:setup/tearDown 方法仅用于选定的测试

ScalaTest: setup/tearDown methods for only selected tests

我知道有 BeforeAndAfter 特征允许我们在套件的每次测试之前和之后执行设置和拆卸操作。

是否有仅在套件前后运行或针对选定测试运行的替代方案?

关于特定测试前后考虑loan pattern

import org.scalactic.Equality
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class LoanPatternExampleSpec extends AnyFlatSpec with Matchers {
  def life(testFun: Int => Any): Unit = {
    println("Doing stuff before the test")
    val meaningOfLife = 42
    testFun(meaningOfLife)
    println("Doing stuff after the test")
  }

  "User" should "do things" in life { i =>
    println(s"My fixture says meaning of life is $i")
    assert(true)
  }
}

输出

sbt:scalatest-seed> testOnly example.LoanPatternExampleSpec
Doing stuff before the test
My fixture says meaning of life is 42
Doing stuff after the test
[info] LoanPatternExampleSpec:
[info] User
[info] - should do things
[info] Run completed in 314 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.

BeforeAndAfterAll 覆盖了在套件前后执行一次的方法。