Basic ScalaCheck usage

March 12, 2016

Given some code to test:

def head[X](xs: List[X]): X = xs.head

We can test it with ScalaCheck by describing properties about it that should be true for arbitrary values:

val headProp =
  org.scalacheck.Prop.forAll { (f: Int => Int, xs: List[Int]) =>
    xs.isEmpty || f(head(xs)) == head(xs map f)
  }

headProp.check

This article is literate Scala:

/***
libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.12.5"
*/
$ curl -s https://earldouglas.com/posts/scalacheck.md | codedown scala > scalacheck.scala
$ sbt -Dsbt.main.class=sbt.ScriptMain scalacheck.scala
+ OK, passed 100 tests.