Properties vs Examples
You'll learn: How property-based testing differs from traditional example-based testing by focusing on universal rules instead of specific cases.
The Fundamental Difference
Traditional testing works with examples: you pick specific inputs and assert their expected outputs. For instance, "When I call add(2, 3), I expect 5." This tests one concrete case.
Property-based testing uses properties: universal statements that must hold true for entire ranges of inputs. Instead of "2 + 3 = 5," you'd write "For any two numbers, adding them should produce the same result as adding them in reverse order."
Thinking in Properties
Properties capture invariants and relationships that transcend individual examples:
- Example thinking: "reversing [1, 2, 3] gives [3, 2, 1]"
- Property thinking: "reversing any list twice returns the original list"
The property is more powerful—it describes behavior for infinite possible lists, not just one.
Why Properties Matter
Properties force you to think about your code's essential characteristics:
- What should always be true?
- What relationships must hold regardless of input?
- What boundaries can never be crossed?
A sorting function has properties like "output length equals input length" and "each output element appears in the input." These apply to any valid input list, not just your three test cases.
The Analogy
Example tests are like checking if a bridge holds one specific car. Property tests verify the bridge's engineering principles—weight distribution, material strength—that ensure it holds any car within design limits.
Key Takeaway: Properties describe universal truths about code behavior across entire input domains, while examples verify specific cases—property-based testing uses properties to automatically test thousands of generated examples.