Define an arbitrary generator for properties
The Arbitrary module defines implicit generator instances for common types.
The implicit definitions of Arbitrary provide type-directed Gens so they are available for properties, generators, or other definitions of Arbitrary.
ScalaCheck expects an implicit Arbitrary instance is in scope for Props that are defined with functions, like Prop.forAll and so on.
For instance, the definition for Arbitrary[Boolean]
is used by Prop.forAll
to automatically provide a Gen[Boolean]
when one of the parameters is a Boolean
:
Prop.forAll { (b: Boolean) =>
b || !b
}
Thanks to Arbitrary
, you don't need to provide an explicit Gen
instance to Prop.forAll
. For instance, this is unnecessary:
val genBool: Gen[Boolean] = Gen.oneOf(true,false)
Prop.forAll(genBool) { (b: Boolean) =>
b || !b
}
Since an arbitrary Gen
for Boolean
is defined in Arbitrary
, it can be summoned with Arbitrary.arbitrary
in cases where you need to provide one explicitly:
val genBool: Gen[Boolean] = Arbitrary.arbitrary[Boolean]
val genSmallInt: Gen[Int] = Gen.choose(0, 9)
Prop.forAll(genBool, genSmallInt) { (b: Boolean, i: Int) =>
i < 10 && b || !b
}
For a user-defined MyClass
, writing the following requires that there exists an implicit Arbitrary[MyClass]
instance:
Prop.forAll { (myClass: MyClass) =>
...
}
The implicit definition of Arbitrary[MyClass]
would look like:
implicit val arbMyClass: Arbitrary[MyClass] = Arbitrary {
...
}
The factory method Arbitrary(...)
expects a generator of type Gen[MyClass]
then it will return an instance of Arbitrary[MyClass]
.
Attributes
- Companion
- object
- Source
- Arbitrary.scala
- Graph
-
- Supertypes
-
trait Serializableclass Objecttrait Matchableclass Any