【问题标题】:Is there a scalaTest method or attribute that can be used to run ONLY once just after all tests in all suites是否有一个 scalaTest 方法或属性可以在所有套件中的所有测试之后仅运行一次
【发布时间】:2018-05-16 00:51:14
【问题描述】:

我有一组测试套件也会增长,我需要运行一个 testcleanup 任务,该任务应该在所有测试完成执行之后和测试进程退出之前只运行一次。这类似于 .NET AssebmlyCleanup,但我在 Scala/Scalatest 世界中找不到等效的东西,而无需编写自定义代码,是吗?

谢谢

【问题讨论】:

    标签: scala automated-tests scalatest


    【解决方案1】:

    我一直在考虑如何解决这个问题,一种方法是在我们的build.sbt 中覆盖一点testtestOnly。 所以假设我们在src/test/scala 下有以下两个套件:

    class Suite1 extends FlatSpec{
      "Test1 in Suite1" should "succeed" in{
        succeed
      }
    }
    

    class Suite2 extends FlatSpec{
      "Test1 in Suite2" should "succeed" in{
        succeed
      }
    }
    

    现在让我们在 /project/ 文件夹下添加一个 CleanUp.scala 对象,我们的清理工作将在其中进行:

    object CleanUp{
      def cleanUp:Unit = println("Cleaning up after all suites are completed.")
    }
    

    这是一个最小的示例,实际上您可能需要进行任何复杂的清理。 现在在我们的build.sbt 中添加以下内容:

    (test in Test) := {
      val testsResult = (test in Test).value
      CleanUp.cleanUp
      testsResult
    }
    
    (testOnly in Test) := {
      (testOnly in Test).evaluated
      CleanUp.cleanUp
    }
    

    这会覆盖 testtestOnly 任务的默认行为,因此将在所有套件(或所有由用户套件指定)执行后应用清理。

    例如,这是我对新的testOnly 的 sbt 控制台检查:

    [IJ]sbt:AfterAllTests> testOnly Suite1
    [info] Suite1:
    [info] Test1 in Suite1
    [info] - should succeed
    [info] Run completed in 150 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.
    Cleaning up after all suites are completed.
    [success] Total time: 0 s, completed Dec 2, 2017 12:19:48 AM
    [IJ]sbt:AfterAllTests> 
    

    这里是新test的检查:

    [IJ]sbt:AfterAllTests> test
    [info] Suite2:
    [info] Test1 in Suite2
    [info] - should succeed
    [info] Suite1:
    [info] Test1 in Suite1
    [info] - should succeed
    [info] Run completed in 164 milliseconds.
    [info] Total number of tests run: 2
    [info] Suites: completed 2, aborted 0
    [info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
    [info] All tests passed.
    Cleaning up after all suites are completed.
    [success] Total time: 2 s, completed Dec 2, 2017 12:28:25 AM
    [IJ]sbt:AfterAllTests> 
    

    如您所见,清理被调用。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 2013-03-03
      • 2021-09-30
      • 2015-09-09
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多