最近开始在 Scala 中编码,我尝试编写一些基于属性的测试用例。在这里,我试图生成模拟我正在测试的系统的原始数据。目标是首先生成基本元素(ctrl
和idz
),然后使用这些值生成两个类(A1
和B1
),最后检查它们的属性。我首先尝试了以下 -
import org.scalatest._
import prop._
import scala.collection.immutable._
import org.scalacheck.{Gen, Arbitrary}
case class A(
controller: String,
id: Double,
x: Double
)
case class B(
controller: String,
id: Double,
y: Double
)
object BaseGenerators {
val ctrl = Gen.const("ABC")
val idz = Arbitrary.arbitrary[Double]
}
trait Generators {
val obj = BaseGenerators
val A1 = for {
controller <- obj.ctrl
id <- obj.idz
x <- Arbitrary.arbitrary[Double]
} yield A(controller, id, x)
val B1 = for {
controller <- obj.ctrl
id <- obj.idz
y <- Arbitrary.arbitrary[Double]
} yield B(controller, id, y)
}
class Something extends PropSpec with PropertyChecks with Matchers with Generators{
property("Controllers are equal") {
forAll(A1, B1) {
(a:A,b:B) =>
a.controller should be (b.controller)
}
}
property("IDs are equal") {
forAll(A1, B1) {
(a:A,b:B) =>
a.id should be (b.id)
}
}
}
在终端中运行sbt test
给了我以下信息 -
[info] Something:
[info] - Controllers are equal
[info] - IDs are equal *** FAILED ***
[info] TestFailedException was thrown during property evaluation.
[info] Message: 1.1794559135007427E-271 was not equal to 7.871712821709093E212
[info] Location: (testnew.scala:52)
[info] Occurred when passed generated values (
[info] arg0 = A(ABC,1.1794559135007427E-271,-1.6982696700585273E-23),
[info] arg1 = B(ABC,7.871712821709093E212,-8.820696498155311E234)
[info] )
现在很容易看出为什么第二个属性失败了。因为每次我屈服A1
并且我为而不是因为它是一个常数而B1
产生不同的价值。以下是我的第二种方法,其中,我创建嵌套以尝试实现我的目标 -id
ctrl
for-yield
case class Popo(
controller: String,
id: Double,
someA: Gen[A],
someB: Gen[B]
)
trait Generators {
val obj = for {
ctrl <- Gen.alphaStr
idz <- Arbitrary.arbitrary[Double]
val someA = for {
x <- Arbitrary.arbitrary[Double]
} yield A(ctrl, idz, someA)
val someB = for {
y <- Arbitrary.arbitrary[Double]
} yield B(ctrl, idz, y)
} yield Popo(ctrl, idz, x, someB)
}
class Something extends PropSpec with PropertyChecks with Matchers with Generators{
property("Controllers are equal") {
forAll(obj) {
(x: Popo) =>
forAll(x.someA, x.someB) {
(a:A,b:B) =>
a.controller should be (b.controller)
}
}
}
property("IDs are equal") {
forAll(obj) {
(x: Popo) =>
forAll(x.someA, x.someB) {
(a:A,b:B) =>
a.id should be (b.id)
}
}
}
}
以第二种方法运行sbt test
告诉我所有测试都通过了。
[info] Something:
[info] - Controllers are equal
[info] - IDs are equal
[info] ScalaTest
[info] Run completed in 335 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
有没有更好/替代的方法来重现我想要的结果?嵌套forAll
对我来说似乎相当笨重。如果我要R -> S -> ... V -> W
在我的依赖图中有对象共享元素,那么我将不得不创建尽可能多的嵌套forAll
.