Video in progress

Staff 🧪 Testing

When is property-based testing more useful than ordinary example-based tests, and how do you introduce it into a project?

Where the input space is large and you can state the invariant precisely: money calculation, serialization round trips, parsers, state machines, two implementations that must give the same result. In Java, jqwik runs such tests on the JUnit 5 platform and shrinks a failing case down to the smallest example.

📖 Answer

An example-based test checks the cases you thought of. A property-based test says "this condition holds for any input" and generates hundreds of random inputs itself, including cases you didn't think of.

class RevenueSplitProperties {

    @Property(tries = 1000)
    void splitNeverLosesOrCreatesMoney(
            @ForAll @LongRange(min = 0, max = 50_000_000) long totalTiyin,
            @ForAll @Size(min = 1, max = 20) List<@IntRange(min = 1, max = 10_000) Integer> minutesWatched) {

        Map<Integer, Long> shares = splitter.split(totalTiyin, minutesWatched);

        assertThat(shares.values().stream().mapToLong(Long::longValue).sum()).isEqualTo(totalTiyin);
        assertThat(shares.values()).allMatch(v -> v >= 0);
    }
}

A test like this finds a rounding bug immediately: split 100 tiyin among 3 authors and you get 33+33+33 = 99, so one tiyin is gone. jqwik "shrinks" the failing case and shows the simplest example: total=1, minutes=[1, 1].

Kinds of good invariants:

  • round trip: deserialize(serialize(x)) == x;
  • conservation: the sum of money, the number of elements;
  • oracle: a new fast implementation gives the same result as the old simple one;
  • idempotence: f(f(x)) == f(x);
  • state machine: after a random sequence of actions the invariant isn't broken (ActionChain in jqwik).

Introduction strategy: not the whole project, but first 2-3 critical modules. Logging the seed and turning failing seeds into ordinary regression tests is a must, otherwise you get "flaky"-looking results that fail once in CI and never show up again. Tune the number of tries to the CI time.

When it's not worth it: CRUD endpoints, UI logic where the invariant is hard to express; plain examples are clearer and easier to read there.