Generators in ScalaCheck

Learn how to use and compose generators in ScalaCheck.

Automatic generators

We can unleash the full power of property-based testing with automatic generators. Different from table-driven property checking, generator-based tests can benefit from automatic generators of class instances. Normally, such an automatic generation tries to cover all the edge cases of our input domain.

We can’t generate input automatically with ScalaTest alone. In Scala the most popular property-based testing library is ScalaCheck. We’ll add it to our project (line 6).

Press + to interact
build.sbt
Dependencies.scala
object Dependencies {
object org {
object scalatestplus {
val `scalacheck-1-17` = "org.scalatestplus" %% "scalacheck-1-17" % "3.2.15.0"
}
}
}

In this lesson, we’ll see how we can leverage ScalaCheck to generate values for us.

Basic generation: the Properties class

The most basic form of property-based checking in ScalaCheck makes use of the Properties class. In this case, ScalaTest is not even necessary; we can write a property-based test suite simply by creating a Scala object (not a class—tests won’t run) extending ScalaCheck’s Properties.

We can start experimenting by writing a specification for the price of a ...