🪟 Windows TippsBitLocker stuck on Decrypting or Encrypting in Windows 11(17.09.2026 um 00:29 Uhr)
🕵️ SicherheitslückenCVE-2026-69110 | Microck opencode-studio up to 2.4.3 missing authentication(17.09.2026 um 03:21 Uhr)
🪟 Windows TippsBitLocker stuck on Decrypting or Encrypting in Windows 11(17.09.2026 um 00:29 Uhr)
🕵️ SicherheitslückenCVE-2026-69110 | Microck opencode-studio up to 2.4.3 missing authentication(17.09.2026 um 03:21 Uhr)
🔧 Programmierung 🕛 vor 3 Monaten 11 Min Lesezeit
0

Property-Based Testing for Domain Rules in PHP

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht


  • Book: + | | into a PHPUnit 11 project, writing property tests for two real domain invariants (Money::add commutativity and OrderTotal monotonicity), 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 of Money values 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:





    1. Edge values. Zero, negative numbers, PHP_INT_MAX, currencies your team doesn't ship to yet.


    2. 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.


    3. 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::withLine as it was in the example-based version:




    CODE
    public 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:




    CODE
    public 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:




    CODE
    1) 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 (Money arithmetic, OrderTotal monotonicity, Email round-trip) are properties. The use-case orchestrations (creating an order issues exactly one OrderCreated event 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 Money or Order has 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.



    Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework



    Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.

    Vollständiger Original-Artikel
    Den kompletten Beitrag mit allen Details direkt auf dev.to lesen.
    ↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
2 Quellen
CVE-2026-92597 | Nodemailer up to 9.0.x Addressparser lib/addressparser input validation (EUVD-2026-81297)
1 Quelle
BitLocker stuck on Decrypting or Encrypting in Windows 11
1 Quelle
CVE-2026-92599 | hapijs joi up to 17.13.6/18.0.0-18.2.5 isoDate Joi.string.isoDate redos (EUVD-2026-81299)
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Property-Based Testing for Domain Rules in PHP

Thematisch verwandte Begriffe: PropertyBased, Testing, Domain, Rules · 6 Treffer

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...