我有一组测试套件也会增长,我需要运行一个testcleanup任务,该任务应该在所有测试完成执行之后和测试进程退出之前运行一次。这类似于.NET AssebmlyCleanup,但我无法在Scala / Scalatest世界中找到相同的东西,而不必自定义代码,是吗?
由于
答案 0 :(得分:5)
我一直在考虑如何处理此问题,一种方法是在test
中覆盖testOnly
和build.sbt
位。
因此,假设我们在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
}
这会覆盖test
和testOnly
任务的默认行为,因此在执行所有套件(或用户套件指定的所有套件)之后将应用清理。
例如,这是我对新testOnly
:
[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>
如您所见,可以调用cleanup。 希望这会有所帮助。