我想测试REST API的所有方法是否都包含在测试中。所有http调用都记录在一个可变的集合中,我有一段代码来检查规范和记录的api调用的结果集之间的对应关系。
我可以将这个检查放在FunSuite末尾的一个单独的< code>test中,它将在所有其他测试之后执行。然而,有两个问题:我必须将它复制粘贴到每个测试API的文件中,并确保它在文件的末尾。
使用公共特征不起作用:父类的测试在子类的测试之前执行。将测试放在After All
中也不起作用:calatest
会吞下其中抛出的所有异常(包括测试失败)。
有没有办法在没有样板的情况下运行一些测试?
就我个人而言,我会使用专门的覆盖工具,例如sco平均。一个优势是避免全局状态。
尽管如此,根据问题,在所有测试之后执行测试的方法是通过套件
和之前和之后的特征
,例如
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)
}
}
你好,斯卡拉
@DoNotDiscover
class HelloSpec extends FlatSpec with Matchers {
"The Hello object" should "say hello" in {
GlobalMutableState.set.add(1)
"hello" shouldEqual "hello"
}
}
Goodbye规范.scala
@DoNotDiscover
class GoodbyeSpec extends FlatSpec with Matchers {
"The Goodbye object" should "say goodbye" in {
GlobalMutableState.set.add(2)
"goodbye" shouldEqual "goodbye"
}
}
现在执行 sbt 测试
给出类似的东西
[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