ScalaCheck: Property-based testing for Scala

ScalaCheck is a library written in Scala and used for automated property-based testing of Scala or Java programs. ScalaCheck was originally inspired by the Haskell library QuickCheck, but has also ventured into its own.

ScalaCheck has no external dependencies other than the Scala runtime, and works great with sbt, the Scala build tool. It is also fully integrated in the test frameworks ScalaTest and specs2. You can of course also use ScalaCheck completely standalone, with its built-in test runner.

ScalaCheck is used by several prominent Scala projects, for example the Scala compiler and the Akka concurrency framework.

News

Quick start

Specify some of the methods of java.lang.String like this:

import org.scalacheck.Properties
import org.scalacheck.Prop.forAll

object StringSpecification extends Properties("String") {

  property("startsWith") = forAll { (a: String, b: String) =>
    (a+b).startsWith(a)
  }

  property("concatenate") = forAll { (a: String, b: String) =>
    (a+b).length > a.length && (a+b).length > b.length
  }

  property("substring") = forAll { (a: String, b: String, c: String) =>
    (a+b+c).substring(a.length, a.length+b.length) == b
  }

}

Then compile and run the tests with ScalaCheck’s command line test runner like this:

$ scalac -cp scalacheck_2.11-1.12.0.jar StringSpecification.scala

$ scala -cp .:scalacheck_2.11-1.12.0.jar StringSpecification
+ String.startsWith: OK, passed 100 tests.
! String.concat: Falsified after 0 passed tests.
> ARG_0: ""
> ARG_1: ""
+ String.substring: OK, passed 100 tests.

As you can see, the second property was not quite right. ScalaCheck discovers this and presents the arguments that make the property fail, two empty strings. The other two properties both pass 100 test rounds, each with a randomized set of input parameters.

You can also use sbt to run ScalaCheck tests.