Book: + | | into a PHPUnit 11 project, writing property tests for two real domain invariants (Money::addcommutativity andOrderTotalmonotonicity), and a concrete refactor where a property test catches a bug example-based tests had missed for a year.
Why example-based testing runs out of room
Example-based tests have one job: pin the behavior you remembered to think about. They are great at documenting intent and catching regressions on known cases. They are terrible at finding the cases you never thought of.
A domain rule like adding money is commutative is not really a statement about
100 + 200. It is a statement about every pair ofMoneyvalues in the same currency. Writing one example per pair is impossible. Writing the rule once and asking the framework to try a thousand pairs is the obvious move.
Three categories of bug live in the gap between examples:
Edge values. Zero, negative numbers,PHP_INT_MAX, currencies your team doesn't ship to yet.
Combinations. A method that works for(a, b)but breaks for(b, a). A reducer that works on lists of length 2 but breaks on length 1 or empty.
Round-trips. Serialize then deserialize. Encode then decode. Persist then load. The example-based test uses the same fixture for both halves and the bug stays hidden because the round-trip never sees a value the team didn't already think of.
Property-based testing catches all three. The framework isn't clever. You are just forced to write down the rule instead of a sample of it.
The refactor where the property test earned its keep
Here is
Order::withLineas it was in the example-based version:
CODEpublic function withLine(Line $line): self
{
$clone = clone $this;
$clone->lines[] = $line;
return $clone;
}
public function total(): int
{
return array_sum(
array_map(
fn (Line $l): int => $l->price * $l->quantity,
$this->lines,
),
);
}
A teammate opens a PR to support free-line items. A line where price is zero is fine, but they also want to support a discount line (a line whose subtotal is subtracted from the running total instead of added). They wire it in:
CODEpublic function total(): int
{
$sum = 0;
foreach ($this->lines as $line) {
$sum += $line->isDiscount
? -1 * $line->price * $line->quantity
: $line->price * $line->quantity;
}
return $sum;
}
The example-based tests still pass. They never used a discount line, so the new branch is exercised only by the two new tests the PR author wrote, both of which use a non-discount baseline and a discount on top. Both pass.
The property test fails on the first run:
CODE1) Tests\Domain\OrderPropertyTest::testOrderTotalIsMonotonic
Failed asserting that -200 is greater than or equal to 0.
shrunk to:
existing: []
extra: [200, 1] (with isDiscount=true)
The shrunken counterexample is unambiguous: an empty order, then one discount line of
(200, 1), produces a total of-200. The monotonicity invariant is broken. The PR author has two ways out:
- Decide that discount lines should clamp at the running total (
max(0, sum - discount)). - Decide that the invariant is wrong, that orders are allowed to go negative, and update the property test (and the spec it documents) to say
assertGreaterThanOrEqual(-MAX_DISCOUNT, $after).
Either resolution is fine. The point is that the property test forced the conversation to happen before the PR merged, by stating a domain rule clearly enough that the runtime could check it. The example-based tests would have shipped the regression and let the support team find it.
When to reach for a property test, and when not to
Property-based testing earns its keep when the rule is algebraic: associativity, commutativity, identity, idempotency, monotonicity, round-trips, invariants over a state machine. It is wasted on rules that are essentially fixtures. The welcome email subject line says "Welcome" is a value, not a property, and an example test is the right shape.
A rough decision rule:
- The rule is a statement about every input from some class → property test.
- The rule is a statement about this input → example test.
- You can describe the rule as a one-line invariant that holds across many cases → property test.
- You can only describe it by enumerating cases → example test.
Most domain code in a clean-architecture PHP service has both kinds of rule. The entity invariants (
Moneyarithmetic,OrderTotalmonotonicity,Emailround-trip) are properties. The use-case orchestrations (creating an order issues exactly oneOrderCreatedevent with the right payload) are examples. Write both. The example tests document intent and read well in code review. The property tests stop the bugs you didn't think of from reaching production.
The Eris suite for a moderately complex domain runs in a couple of seconds even at 200 cases per property. The cost is negligible. The payoff is that the next PR that introduces a subtle change to
MoneyorOrderhas to pass a much wider net than the team's collective memory of edge cases. Domain rules belong in code, not in the heads of whoever was on the team three years ago. Property tests are how you write them down.
If this was useful
A domain that survives framework migrations is one where the rules are encoded — in types, in invariants, and in tests that check them across more cases than any human would write by hand. The book walks the full hexagonal layout in PHP 8.3+, with the testing chapter going deeper into property tests, contract tests, and in-memory adapters across the use-case layer. If this post lined up with where your codebase hurts, the book is the long version of the same argument.
Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.
↗ Original-Artikel auf dev.to lesenVollständiger Original-ArtikelDen kompletten Beitrag mit allen Details direkt auf dev.to lesen.
Property-Based Testing for Domain Rules in PHP
- ▸ Why example-based testing runs out of room
- ▸ Wiring Eris into PHPUnit 11
- ▸ Property 1: Money::add commutativity and associativity
- ▸ Property 2: OrderTotal is monotonic in line count
- ▸ The refactor where the property test earned its keep
- ▸ When to reach for a property test, and when not to
- ▸ If this was useful

SOCIAL SHARE CARD GENERATOR