Independent Tests and Fresh Fixtures
Tests should establish the state they rely on so running one case independently produces the same outcome as running the suite.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Find leaked state
If one test appends to a shared list and a later test expects the original length, running them together may fail. Running the later test alone may pass. The behavior follows mutable object sharing.
Allocate one fixture per test
Create or reset writable data for each test, then check for expected cleanup. Immutable reference data can be shared freely when the test never alters it. A test with two passes in reversed order can expose an unintended program state dependency.[1]
Make the starting resource belong to the test
One test adds a route to a table and another expects a newly built table to be empty. If both reuse a mutable module-level table, the second can fail only after the first runs. Construct an independent table per test or reset it with an explicit lifecycle. See shallow copies.
Isolated run of empty-table test: passes
After add-route test with shared data: fails
After giving both fresh tables: outcome independent of order
Check other process-level state too
An environment variable, clock override or cache can persist between tests even if the main object is recreated. Run suspected tests alone and in both orders. Restore external state through the test tool's cleanup mechanism.