我有一个简单的主文件,其中实现了一些随机数生成器。
import java.util.Random
object Main extends App {
trait Generator[+T] {
self =>
def generate: T
def map[S](f:T => S): Generator[S] = new Generator[S] {
def generate = f(self.generate)
}
def flatMap[S](f:T => Generator[S]): Generator[S] = new Generator[S] {
def generate = f(self.generate).generate
}
}
val integers = new Generator[Int] {
val rand = new Random()
def generate = rand.nextInt()
}
val boolean = new Generator[Boolean] {
def generate = integers.generate > 0
}
val booleans = for{i <- integers} yield i > 0
def pairs[T, U](generator1: Generator[T], generator2: Generator[U]) = {
for{i <- generator1; j <- generator2} yield (i, j )
}
val pair = pairs(integers, boolean)
def single[U](x:U):Generator[U] = new Generator[U] {
def generate = x
}
println(integers.generate, boolean.generate, pair.generate)
def lists: Generator[List[Int]] = {
for{
isEmpty <- boolean
l <- if(isEmpty) emptyList else nonEmptyList
} yield l
}
def emptyList = single(List())
def nonEmptyList = for{
head <- integers
tail <- lists
} yield head :: tail
println(lists.generate)
println(lists.generate)
}
我正在尝试使用forAll
表达式构建生成器驱动的测试
import org.scalatest.FunSuite
import org.scalacheck.Prop.forAll
import Main.lists
class MainSuite extends FunSuite{
test("An empty Set should have size 0") {
assert(Set.empty.size == 0)
}
test("Invoking head on an empty Set should produce NoSuchElementException") {
intercept[NoSuchElementException] {
Set.empty.head
}
}
test("Sum of lists increase the size?")
{
forAll { (n:Int) =>
val l1 = lists.generate
val l2 = lists.generate
assert(l1.length + l2.length < l1.length)
}
代码通过所有测试,而它应该在最后一个测试失败。我该如何解决?