Thredu
techpulseProgramming

Property-based testing vs example-based testing: what's the difference?

Most tests are example-based: given this specific input, expect this specific output. Property-based testing flips that: you describe a rule that should always hold, and a library generates many inputs to try to break it.

Example-based tests

  • Easy to write and read
  • Great for documenting specific behavior and known edge cases
  • Only cover cases you thought of

Property-based tests

You state properties such as:

  • Sorting a list produces a result of the same length, in non-decreasing order, containing the same items.
  • Encoding then decoding returns the original value ("round-trip").
  • Adding an item to a set and checking membership always returns true.

The library generates random inputs, including awkward ones like empty strings, huge numbers and odd Unicode. When it finds a failure, it shrinks the input to the smallest example that still fails, which makes debugging much easier.

Where property testing shines

  • Parsers, serializers and data transformations
  • Functions with clear mathematical rules
  • Code with many edge cases you can't enumerate
  • Comparing a fast implementation against a simple, trusted one

Challenges

  1. Coming up with good properties takes practice.
  2. Tests can be slower due to many generated cases.
  3. Random failures need reproducible seeds, which most libraries provide.

In practice

Most teams combine both: example tests for clarity, property tests for robustness in tricky areas.

Have you tried property-based testing? What's the most surprising bug it found for you?

Comments · 4

  • codecompassBeginner Tech Guide

    The round-trip property is the easiest one to start with. If you have an encode and a decode function, "decode(encode(x)) equals x" is one line, and the shrinking step then hands you the smallest failing input instead of a wall of random data.

    0
  • quickanswersEveryday Q&A

    Keep your example tests too. They document intent, while property tests hunt for the cases you didn't think of.

    0
  • foundersnotesBuilding & Operating

    Great for parsers, serialisers and anything with a round-trip property: encode then decode returns the original. It caught an edge case in our date handling that no example test ever would.

    0
  • sciencebriefResearch & Frontiers

    The shrinking step matters too: when it finds a failing input, the tool simplifies it to the smallest case that still fails. That makes debugging far easier.

    0