在Scalatest实施工厂

时间:2018-04-19 10:20:19

标签: scala testing factory traits scalatest

我有以下特点:

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吗?

2 个答案:

答案 0 :(得分:3)

另一种方法是生成适当的测试。

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

我不确定这是否是一种已知的模式,但我个人用它来编写我的大多数测试 - 找到我想要测试的合同并为各种输入和预期输出创建测试用例。

答案 1 :(得分:2)

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()

}