How-To Guide

How to Implement Property-Based Testing

Test with properties: state an invariant, generate many inputs, shrink a failure to a minimal case, and keep the run reproducible with a seed.

On this page

  1. Introduction
  2. State a property that must always hold
  3. Let the framework generate the inputs
  4. Shrink the failure to a minimal case
  5. Make the run reproducible with a seed
  6. Test the property and its counterexamples
  7. Common pitfalls
  8. Conclusion

Introduction

An example test asserts the output for one input, which is a sample of the behavior. It cannot cover the inputs the author did not think of, and those are where the bugs are: the empty string, the negative number, the unicode character, the value at a boundary. Property-based testing states an invariant that must hold for all inputs and generates many inputs to try to break it, then shrinks a failure to a minimal example.

This tutorial covers stating a property, generating inputs, shrinking a failure, and making the run reproducible. The examples use a property framework, and the approach applies in any language with a property-testing library.

State a property that must always hold

A property is an invariant, true for every valid input, expressed as a function of the input. The classic properties are round-trip (encode then decode returns the original), idempotence (applying twice equals applying once), commutativity (order does not matter), an ordering (the output is sorted), and an equivalence (a fast implementation matches a slow one). Each is a simple statement that should hold without exceptions.

The property should be strong enough to fail when the code is wrong. A property that passes for any output asserts nothing, and a property that restates the implementation asserts only that the code matches itself. Good properties come from the specification: what must be true of the result regardless of how it was computed. State the invariant and let the framework search for a counterexample.

import { fc } from '@fast-check/vitest';

it('encode then decode returns the original', () => {
  fc.assert(
    fc.property(fc.string(), (s) => {
      expect(decode(encode(s))).toBe(s);   // the round-trip invariant
    }),
  );
});

Let the framework generate the inputs

The framework generates inputs from a generator, covering the simple cases and the unusual ones: empty collections, extreme integers, unicode strings, and values with special characters. Over many runs it explores combinations a hand-written example would not, and it reports an input that breaks the property. This is the discovery the technique is for.

Constrain the generator to valid inputs, because the property is about valid inputs only. A generator for an email address should produce valid addresses, not arbitrary strings, and a precondition can filter the invalid ones. A generator that produces an invalid input makes the property fail for a reason unrelated to the code, so keep the generator to the domain.

fc.assert(fc.property(
  fc.array(fc.integer()),                       // many arrays, some empty
  (arr) => {
    const sorted = sortNumbers(arr);
    for (let i = 1; i < sorted.length; i++) {
      expect(sorted[i]).toBeGreaterThanOrEqual(sorted[i - 1]);   // sorted invariant
    }
  },
));

Shrink the failure to a minimal case

When a property fails, the framework shrinks the input to the smallest one that still fails, so the failure is a small, understandable case rather than a large random one. The shrink turns a failure on a hundred-element array into a failure on a two-element one, or a long string into a short one, which points at the cause. The minimal counterexample is the value of the technique.

The framework reports the shrunk input and the seed, so you can replay the failure. Use the shrunk input as a regression test, adding it as a fixed example test alongside the property, so the specific case is checked on every run and the property continues to search for others. The combination of a property and its known counterexamples is a strong suite.

# a failing run reports the seed and the shrunk counterexample
# Counterexample: [3, 1]
# Seed: 1745620013
# add the shrunk case as a fixed test, and keep the property searching

Make the run reproducible with a seed

Random input generation makes a failure depend on the run, so the framework prints a seed that reproduces it. Set the seed to replay the exact run, which makes the failure reproducible and debuggable. A failure that cannot be reproduced is a rumor; a failure with a seed is a case you can run again and fix.

For determinism, generate the random values for the inputs from a seeded generator, so a given seed always produces the same inputs. This makes a property test as reproducible as an example test when you fix the seed, while still exploring many inputs when the seed varies. Keep the seed in the failure output so a CI failure can be replayed locally.

Test the property and its counterexamples

Run the property in the suite so it searches on every run, and add each known counterexample as a fixed test so the specific case is checked even if the property’s search does not hit it. Test that the property fails on a known-bad implementation, so the property is strong enough to catch the bug, rather than passing trivially. A property that never fails on a broken implementation is too weak.

# prove the property catches a bug: run it against a deliberately broken sort
node -e '
const { brokenSort } = require("./broken");
// the property must fail on brokenSort, proving it is strong enough
'

Common pitfalls

A property so weak it never fails, a property that restates the implementation so it only agrees with itself, a generator that produces invalid inputs so the failure is unrelated, a non-reproducible failure with no seed, and not adding the shrunk counterexample as a regression test are the recurring mistakes. A strong invariant, a specification-derived property, a domain-constrained generator, a printed seed, and fixed counterexamples address them.

Conclusion

Property-based testing states an invariant and searches for a counterexample with generated inputs. State a property that must always hold, generate varied valid inputs, shrink a failure to a minimal case, make the run reproducible with a seed, and add the counterexample as a regression test. Self-check by asserting the property fails on a deliberately broken implementation and that the shrunk case is small and clear. Then the tests find the edge cases an example would miss.

Sources: fast-check: Property based testing, Hypothesis: Property based testing, Property-based testing (Wikipedia).

FAQ

How is property testing different from example testing?
An example test asserts the output for one input. A property test asserts an invariant for many generated inputs, so it finds edge cases the author did not think of, such as an empty string, a negative number, or a value with a special character.
What makes a good property?
An invariant that must hold regardless of the input: round-tripping, idempotence, commutativity, an ordering, or that one form preserves a value. It should be simple to state and should fail loudly when the code is wrong, rather than being so weak it never fails.

Related Examples