【问题标题】:How to ensure that test is executed after all tests in scalatest?如何确保在 scalatest 中的所有测试之后执行测试?
【发布时间】:2019-10-03 06:43:16
【问题描述】:

我想测试 REST API 的所有方法是否都包含在测试中。 所有 http 调用都记录到一个可变集合中,我有一段代码可以检查规范和记录的 api 调用结果集之间的对应关系。

我可以将此检查放在 FunSuite 末尾的单独 test 中,它将在所有其他测试之后执行。但是,有两个问题:我必须将它复制粘贴到每个测试 API 的文件中,并确保它位于文件末尾。

使用 common trait 不起作用:父类的测试在子类的测试之前执行。将测试放在 afterAll 中也不起作用:scalatest 会吞下所有抛出的异常(包括测试失败)。

有没有办法在没有样板的情况下运行一些测试?

【问题讨论】:

    标签: scalatest


    【解决方案1】:

    我个人会使用专用的覆盖工具,例如scoverage。一个优势是避免全局状态。

    不过,根据问题,在所有测试之后执行测试的方法是通过 SuitesBeforeAndAfterAll 这样的特征

    import org.scalatest.{BeforeAndAfterAll, Suites, Matchers}
    
    class AllSuites extends Suites(
      new FooSpec,
      new BarSpec,
    ) with BeforeAndAfterAll withy Matchers {
    
      override def afterAll(): Unit = {
        // matchers here as usual
      }
    }
    

    这是一个根据问题的全局状态的玩具示例

    AllSuites.scala

    import org.scalatest.{BeforeAndAfterAll, Matchers, Suites}
    
    object GlobalMutableState {
      val set = scala.collection.mutable.Set[Int]()
    }
    
    class AllSuites extends Suites(
      new HelloSpec,
      new GoodbyeSpec
    ) with BeforeAndAfterAll with Matchers {
    
      override def afterAll(): Unit = {
        GlobalMutableState.set should contain theSameElementsAs Set(3,2)
      }
    }
    

    HelloSpec.scala

    @DoNotDiscover
    class HelloSpec extends FlatSpec with Matchers {
      "The Hello object" should "say hello" in {
        GlobalMutableState.set.add(1)
        "hello" shouldEqual "hello"
      }
    }
    

    GoodbyeSpec.scala

    @DoNotDiscover
    class GoodbyeSpec extends FlatSpec with Matchers {
      "The Goodbye object" should "say goodbye" in {
        GlobalMutableState.set.add(2)
        "goodbye" shouldEqual "goodbye"
      }
    }
    

    现在执行 sbt test 会得到类似的结果

    [info] example.AllSuites *** ABORTED ***
    [info]   HashSet(1, 2) did not contain the same elements as Set(3, 2) (AllSuites.scala:15)
    [info] HelloSpec:
    [info] The Hello object
    [info] - should say hello
    [info] GoodbyeSpec:
    [info] The Goodbye object
    [info] - should say goodbye
    [info] Run completed in 377 milliseconds.
    [info] Total number of tests run: 2
    [info] Suites: completed 2, aborted 1
    [info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
    [info] *** 1 SUITE ABORTED ***
    [error] Error during tests:
    [error]     example.AllSuites
    [error] (Test / test) sbt.TestsFailedException: Tests unsuccessful
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2013-01-24
      • 2013-03-03
      • 2021-09-11
      • 1970-01-01
      • 2015-09-13
      • 2015-03-20
      • 2020-06-04
      相关资源
      最近更新 更多