Part II — Intermediate Development · Chapter 10 · Lesson 3 of 6 · 8 min read
Lesson 3: Fixtures, Deterministic Tests, and Boundary Cases
Lesson level: Intermediate
Purpose: Build reliable test data, remove hidden sources of variation, and choose inputs that expose boundary and precedence defects.
Learning objectives
By the end of this lesson, you should be able to:
- design fixtures that are small, named, and independent;
- identify and remove sources of nondeterminism;
- inject time, randomness, and external data instead of reading them directly;
- derive boundary cases from a rule’s thresholds;
- use tables of cases to keep tests readable; and
- diagnose flaky tests systematically.
Release note: syntax and helper names in this lesson are illustrative. Verify them against the installed v0.63 release.
3.1 What a fixture is
A fixture is the known starting state a test needs: input data, configuration, or a prepared object. A good fixture makes the test’s intent obvious by containing only what matters to the behavior under test.
In the order-discount project, a fixture is usually a small map representing one order. All values are synthetic.
let gold_bulk_order = {"tier": "gold", "quantity": 10, "unit_price": 20}
let standard_small_order = {"tier": "standard", "quantity": 2, "unit_price": 20}
3.2 Principles for fixtures
- Small: include only the fields the rule reads.
- Named: the name states the scenario, such as gold_bulk_order.
- Independent: no test depends on another test having run first.
- Immutable by convention: tests should not modify a shared fixture.
- Synthetic: never copy real customer data into a test.
3.3 Builders and variations
When many tests differ by one field, a small builder function creates a valid default and overrides only what the test cares about. This keeps the difference visible.
function make_order(overrides) {
let order = {"tier": "standard", "quantity": 1, "unit_price": 20}
for key in overrides {
order[key] = overrides[key]
}
return order
}
test "gold tier at bulk threshold returns GOLD_BULK" {
let order = make_order({"tier": "gold", "quantity": 10})
assert rules.decide(order)["reason"] == "GOLD_BULK"
}
The test body now shows exactly which inputs matter. A reader does not need to compare two large literals to find the difference.
3.4 Shared state and isolation
Shared mutable state is the most common cause of order-dependent failures. A test that passes alone but fails in the full suite usually reads state that another test changed.
- Create fixtures inside each test or by a builder that returns a fresh value.
- Copy a collection before mutating it.
- Avoid module-level variables that tests update.
- Reset any capability adapter to a known fake before each test.
3.5 Sources of nondeterminism
| Source | Symptom | Remedy |
|---|---|---|
| Current time | Passes today, fails at month end | Pass the time in as a parameter or use a fixed fake clock |
| Randomness | Fails one run in twenty | Use a fixed seed or inject a fake generator |
| Map or set iteration order | Output order changes | Sort keys before comparing, or compare as sets |
| Floating-point arithmetic | Last digit differs | Compare within a stated tolerance |
| Files and environment | Fails on another machine | Use temporary data and inject paths; deny file capabilities by default |
| Network and HTTP | Slow or intermittent failures | Inject a fake transport; never call real services |
| Concurrency timing | Race-dependent results | Use deterministic scheduling or bounded waits |
Deterministic tests give the same result on every run, on every machine, in any order. Without that property, a failure carries no information.
3.6 Inject, do not fetch
The cleanest remedy is dependency injection. The rule receives the value it needs rather than obtaining it itself. This follows the Chapter 9 design: pure rules, narrow adapters, and dependencies that point downward.
// Hard to test: reads the clock inside the rule
function is_promo_active() { return std.datetime.now() < promo_end }
// Easy to test: the caller supplies the instant
function is_promo_active(now, promo_end) { return now < promo_end }
The second form is a pure function. Its tests need no clock, no setup, and no cleanup.
3.7 Floating-point comparisons
Compare computed decimals with a tolerance, not exact equality. State the tolerance in the test so a reader understands the precision the rule guarantees.
let expected = 36.0
let actual = rules.total(order)
assert std.math.abs(actual - expected) < 0.0001
Where the domain allows it, prefer integer minor units such as cents. Integer arithmetic removes a whole class of precision questions.
3.8 Deriving boundary cases
Most rule defects live at thresholds. For every threshold, test the value just below, exactly at, and just above it. This three-point method is the core of boundary testing.
| Rule | Below | At | Above |
|---|---|---|---|
| Bulk threshold: quantity >= 10 | 9 → no bulk | 10 → bulk | 11 → bulk |
| Quantity must be positive | 0 → VALIDATION_ERROR | 1 → valid | 2 → valid |
| Gold tier match | "silver" → not gold | "gold" → gold | "Gold" → not gold (case-sensitive) |
Also test the extremes of each domain: the smallest valid value, the largest permitted value, empty collections, missing fields, null, and values of the wrong type.
3.9 Precedence and overlap cases
When two rules can both apply, the order of evaluation decides the result. Write a case where several conditions are true at once and assert the documented winner. In the order-discount project, a gold customer at the bulk threshold satisfies both GOLD and BULK, and the expected reason is GOLD_BULK.
Then reverse the order of two rules on a scratch copy and confirm that exactly the overlap tests fail. If no test fails, precedence is untested.
3.10 Table-driven tests
When many cases share one assertion shape, put the cases in a table and loop over them. Each row should carry a name so a failure identifies the case.
let cases = [
{"name": "A below bulk", "tier": "standard", "qty": 9, "reason": "NONE"},
{"name": "B at bulk", "tier": "standard", "qty": 10, "reason": "BULK"},
{"name": "C gold at bulk", "tier": "gold", "qty": 10, "reason": "GOLD_BULK"},
{"name": "D zero quantity", "tier": "gold", "qty": 0, "reason": "VALIDATION_ERROR"}
]
test "discount reasons by case" {
for c in cases {
let result = rules.decide(make_order({"tier": c["tier"], "quantity": c["qty"]}))
assert result["reason"] == c["reason"], c["name"]
}
}
A table keeps the data separate from the logic. The risk is that a loop stops at the first failure, so keep each row independent and include the case name in every assertion message.
3.11 Diagnosing flaky tests
- Run the test alone, then in the full suite, then in a random order.
- Run it many times in a loop and record the failure rate.
- Search for time, randomness, ordering, shared state, and external access.
- Remove one suspect at a time and rerun.
- Never silence a flaky test by retrying; fix the cause or quarantine it with a ticket and an owner.
3.12 Common mistakes
| Mistake | Consequence | Correction |
|---|---|---|
| Large shared fixture used by every test | Hidden coupling; one change breaks many tests | Use small builders with explicit overrides |
| Reading the real clock in a rule | Date-dependent failures | Inject the instant |
| Comparing floats with equality | Intermittent last-digit failures | Compare within a tolerance |
| Testing only the middle of a range | Boundary defects survive | Test below, at, and above every threshold |
| Asserting on map print order | Order-dependent failures | Compare fields, or sort first |
| Retrying a flaky test until green | Real defects hidden | Find the nondeterminism and remove it |
3.13 Diagnostic workflow
- Reproduce the failure and record the exact inputs.
- Decide whether the failure is consistent or intermittent.
- For a consistent failure, reduce the input to the smallest failing case.
- For an intermittent failure, look for time, randomness, ordering, and shared state.
- Check whether the expectation or the rule is wrong against the written policy.
- Fix one cause, then rerun the test alone, in the suite, and in a different order.
3.14 Guided practice
- List the fields a minimal fixture needs to test the bulk threshold.
- Write a builder call for a gold-tier order with quantity 9.
- Rewrite a rule that reads the clock so the instant is a parameter.
- List below, at, and above values for a threshold of 100 affected users.
- Explain why a test that passes alone but fails in the suite suggests shared state.
- Name two ways to avoid exact floating-point equality in an assertion.
3.15 Hands-on lab: Make the order-discount suite deterministic
Goal: Rebuild the fixtures for the Chapter 9 project and prove that the suite is deterministic and boundary-complete.
- Replace any large shared fixture with a builder that returns a fresh default order.
- Rewrite three existing tests to use the builder with explicit overrides.
- Add below, at, and above tests for the bulk threshold of 10.
- Add overlap tests for gold customers at the threshold and document the expected winner.
- Convert the cases A–K into one table-driven test with named rows.
- Run the suite five times and in a reversed file order; record that results are identical.
- Introduce a deliberate time or shared-state dependency on a scratch copy, observe the flakiness, and remove it.
Deliverable: The updated tests, a boundary table for every threshold, a record of the repeated runs, and a short note describing the nondeterminism you introduced and how you removed it.
3.16 Review questions
- What makes a fixture good?
- Why should fixtures not be shared and mutated?
- Name four sources of nondeterminism.
- What does it mean to inject a dependency, and why does it help testing?
- Why compare decimals with a tolerance?
- What is the three-point boundary method?
- How do you test that rule precedence is protected?
- Why is retrying a flaky test not a fix?
3.17 Applied challenge
Choose a rule from your own domain that depends on the current time and a threshold. Redesign it so time is injected, write a fixture builder, list its boundary cases in a table, and write the table-driven test. Explain which failures your tests would detect if the time source changed.
Lesson summary
Reliable tests start from small, named, independent fixtures and remove hidden variation by injecting time, randomness, and external data. Boundary cases come directly from thresholds: below, at, and above. Table-driven tests keep many cases readable, and overlap tests protect rule precedence. A flaky test signals hidden nondeterminism that must be found and removed, not retried.
Transition to Lesson 4
The next lesson covers interpreter/VM differential testing, fuzzing, and conformance: running the same program on both execution engines, generating unexpected inputs, and checking behavior against the specification.
Lesson status: Ready for review.