Scalatest中工厂的实现
我有以下特点:Scalatest中工厂的实现,scala,testing,factory,traits,scalatest,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 Match
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
中执行吗?将traitest
转换为抽象类:
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()
}
将
traitest
转换为抽象类:
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()
}
另一种方法是生成适当的测试
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测试的输出
:
[info] Impl1
[info] - should fulfill contract 1
[info] Impl2
[info] - should fulfill contract 1
[info] Impl3
[info] - should fulfill contract 1
我不确定这是否是一个已知的模式,但就我个人而言,我用它来编写我的大多数测试——找到我想要测试的合同,并为各种输入和预期输出集创建测试用例。另一种方法是生成适当的测试
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测试的输出
:
[info] Impl1
[info] - should fulfill contract 1
[info] Impl2
[info] - should fulfill contract 1
[info] Impl3
[info] - should fulfill contract 1
我不确定这是否是一个已知的模式,但就我个人而言,我用它来编写我的大多数测试-找到我想要测试的合同,并为各种输入集和预期输出创建测试用例。您也可以让它更接近工厂:
(,()=>newimpl1())
然后在测试中调用impl()
。如果类型是可变的,则特别有用……您还可以使其更接近工厂:(“Impl1”,()=>newimpl1())
,然后在测试中调用impl()
。如果类型是可变的,则特别有用。。。