在Scalatest实施工厂

问题描述 投票:0回答:2

我有以下特点:

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

scala testing factory traits scalatest
2个回答
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

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


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

}
© www.soinside.com 2019 - 2024. All rights reserved.