我想测试REST API的所有方法是否都被测试覆盖。 所有的http调用都记录在一个可变集中,并且我有一段代码可以检查规范和重新封装的api调用结果集之间的对应关系。
我可以将此检查放在FunSuite末尾的单独test
中,它将在所有其他测试之后执行。但是,有两个问题:我必须将其复制粘贴到每个测试API的文件中,并确保它位于文件末尾。
使用通用特征不起作用:父类的测试先于子类的测试执行。将测试放入afterAll
也不起作用:scalatest
吞没了其中抛出的所有异常(包括测试失败)。
有没有其他样板可以进行所有其他测试?
答案 0 :(得分:2)
我个人会使用专用的覆盖工具,例如scoverage。一种优势是避免全局状态。
尽管如此,按照每个问题,在所有测试之后执行测试的一种方式将是通过Suites
和BeforeAndAfterAll
特质这样
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