Existing generators

Speaking about existing generators, ScalaCheck provides a lot of them out of the box, such as all subtypes of AnyVal, Unit, Function0, chars and strings with different contents (alphaChar, alphaLowerChar, alphaNumChar, alphaStr, alphaUpperChar, numChar, numStr), containers, lists and maps (containerOf, containerOf1, containerOfN, nonEmptyContainerOf, listOf, listOf1, listOfNnonEmptyListOfmapOf, mapOfN, nonEmptyMap), numbers (chooseNum, negNum, posNum), duration, Calendar, BitSet, and even Test.Parameters!

If there is no generator  suitable for the testing purposes available, it is possible to create a custom generator by implementing a Gen class:

sealed abstract class Gen[+T] extends Serializable { self =>
...
def apply(p: Gen.Parameters, seed: Seed): Option[T]
def sample: Option[T]
...
}

This is an abstract class, which is basically just a function taking test parameters and returning an optional value of the required type.

It is partially implemented, but still, it's a bit mundane to extend it manually. Hence new generators are usually implemented by reusing already existing ones. As an exercise, let's implement a generator for literal types:

def literalGen[T <: Singleton](t: T): Gen[T] = Gen.const(t)
implicit val myGen: Arbitrary[42] = Arbitrary(literalGen(42))
val literalProp = forAll((_: 42) == 42).check

In the first line, we're creating a generator factory for literal types by delegating the value generation to the Gen.const. This is safe to do because, by definition, literal types contain just a single value. The second line creates an implicit Arbitrary[42], which is expected to be in scope by the forAll property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.158.32