我有以下特点:
trait TraitToTest{
def doSome(): Unit
}
和一些实现
class Impl1 extends TraitToTest
class Impl2 extends TraitToTest
class Impl3 extends TraitToTest
//...
我有一些TraitToTest
的一般合同,每个实施必须坚持。我可以将合同描述如下:
class TraitTest extends FunSpec with Matchers{
describe("TraitTest general contracts"){
it("should test contract 1"){
val impl = //some impl of TraitToTest
//the test
}
}
}
问题是我不想为TraitToTest
的每个实现复制TraitToTest
一般合同。我只是想将实现实例作为一种工厂提供......
有可能在Scalatest
吗?
另一种方法是生成适当的测试。
class TraitToTest extends FunSpec {
val testCases =
List(
("Impl1", new Impl1()),
("Impl2", new Impl2()),
("Impl3", new Impl3())
)
testCases.foreach {
case (name, impl) =>
describe(name) {
it("should fulfill contract 1") {
// tests for impl go here
}
}
}
sbt test
的输出:
[info] Impl1
[info] - should fulfill contract 1
[info] Impl2
[info] - should fulfill contract 1
[info] Impl3
[info] - should fulfill contract 1
我不确定这是否是一个已知的模式,但我个人用它来编写我的大多数测试 - 找到我想要测试的合同并为各种输入和预期输出创建测试用例。
将TraitTest
转换为抽象类:
abstract class TraitTest extends FunSpec with Matchers {
val impl: TraitToTest
describe("TraitTest general contracts"){
it("should test contract 1"){
impl.doSome()
}
}
}
实现套件将实例化相应的特征:
class Impl1TestSuite extends TraitTest {
override val impl = new Impl1()
}