liveBook · Manning

Property-based testing library

As explained in Functional Programming in Scala, Second Edition

A property-based testing library is a software library that specifies behavioral properties, generates constrained test cases, and evaluates the resulting tests.

A property-based testing library separates behavioral specifications from test-case construction. You state properties and high-level input constraints; the library generates satisfying cases and checks whether the properties hold. section 8.0

A typical workflow combines four parts:

  • Define a generator such as Gen[List[Int]] that produces constrained values, such as lists containing random integers from 0 through 100. section 8.1
  • Give Prop.forAll a generator and a predicate of type A => Boolean; the resulting property requires every generated value to satisfy the predicate. section 8.1
  • Compose properties with && so a specification succeeds only when none of its generated cases falsifies either property. section 8.1
  • Run check to generate test cases, report success, or print a counterexample that supports debugging. section 8.1

Testing list reversal

A specification can require that reversing a list twice returns the original list and that the first optional element matches the reversed list’s last optional element. A deliberately false property, such as requiring every list to equal its reverse, is falsified with a concrete counterexample such as List(0, 1).

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains generators, predicates, composition, checking, and counterexamples, but stops short of library implementation internals.
Examples
Uses constrained integer-list generators, list-reversal laws, successful checks, and a failing property with a printed counterexample.
What it assumes
Assumes familiarity with APIs and functions while introducing generators, properties, predicates, and automated law checking through examples.
What you can do after
Apply it via ScalaCheck to express properties, generate constrained inputs, run checks, and investigate falsifying cases.
How it connects
Connects generators, predicates, properties, combinators, APIs, and algebraic laws.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.