FP in Scala的第8章讨论了基于属性的测试,并介绍了如何从头开始构建一个库。下面是API的高级摘要:
//generator of random test cases
case class Gen[+A](sample: State[RNG,A])
//generator of random test cases with specified size
case class SGen[+A](g: Int => Gen[A])
//property that runs assertion
case class Prop(run: (MaxSize,TestCases,RNG) => Result)
//combines random generator with predicates and returns a property
def forAll[A](g: Int => Gen[A])(f: A => Boolean): Prop
字符串
下面的forAll
实现首先创建一个属性序列,每个属性的大小为0,1,. max(或n,以较小者为准)。然后,它通过将它们与&&
组合来创建单个属性,同时将每个属性的测试用例数设置为casesPerSize
def forAll[A](g: Int => Gen[A])(f: A => Boolean): Prop = Prop {
(max,n,rng) =>
val casesPerSize = (n - 1) / max + 1
val props: Stream[Prop] =
Stream.from(0).take((n min max) + 1).map(i => forAll(g(i))(f))
val prop: Prop =
props.map(p => Prop { (max, n, rng) =>
p.run(max, casesPerSize, rng)
}).toList.reduce(_ && _)
prop.run(max,n,rng)
}
型
我不明白的是为什么casesPerSize计算为
val casesPerSize = (n - 1) / max + 1
型
举一个具体的例子,如果我假设n=95, max=10
,那么将有11个大小从0到10的属性,每个属性将生成10个测试用例。由于只有1个大小为0的唯一测试用例,这仍然意味着110 - 9 = 101个唯一测试用例。那么如何确保不超过n个测试用例被生成?
1条答案
按热度按时间fcy6dtqo1#
我认为计算casesPerSize的公式选择得相当随意。以及计算最大测试长度的公式take((n min max)+ 1)。