Property-Based Testing with Shrinking

Use generated examples to check a precise invariant and shrink any failure to a case that preserves the relevant preconditions.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. State the relationship between input and output
  2. Shrinking should preserve why the input is valid

State the relationship between input and output

For a sort on integer lists, one property checks nondecreasing output and another checks preservation of value multiplicities. Either property alone is insufficient: an always-empty result is sorted, and a copy preserves counts without ordering. Generators should exercise equal elements, already-sorted input and small pathological arrangements, in addition to broadly distributed cases. Include the random seed and input in the report.

Shrinking should preserve why the input is valid

If a failure appears in a long list, try removing chunks or simplifying values while still checking the failure. A sorting failure driven by two equal keys may shrink to a pair. For an operation taking sorted input, shrink within that precondition so the resulting failure remains relevant. Differential testing offers a second oracle when a simple reference exists. Hoare specifications articulate stronger claims that testing can sample but does not prove.[1]

References

  1. Koen Claessen and John Hughes, QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs ↩