22.4 · Fakes, mocks and the inputs that make tests random
Hard-to-test code is usually code that reaches out for its dependencies and for “now”. Testability is a design property: make the edges explicit and the tests become small and boring.
Mental model. A test controls every input to the code under test: collaborators, time, randomness, locale, files. Anything it cannot control becomes a flake.
Test doubles
Dummies, stubs, fakes, spies and mocks, and when each one fits.
- What is the difference between dummies, stubs, fakes, spies and mocks, and how do you decide which to use?
These are all test doubles: stand-ins for a real collaborator, made possible by depending on a protocol (or a closure) instead of a concrete type, with the…
Determinism
Time, randomness, locale, time zone and the file system.
- What makes a test non-deterministic, and how do you control time zones, locales, randomness, UUIDs and the file system?
A test is deterministic if the same code and inputs give the same result on every machine and every run. It stops being so when it silently depends on ambient…
More in Testing
- 22.1 · The pyramid, and what not to test
- 22.2 · XCTest and Swift Testing
- 22.3 · Async tests, expectations and controlling time
- 22.5 · Snapshot tests and UI tests
- 22.6 · Testing SwiftUI, tvOS focus, and watchOS logic
- 22.7 · Flakes, hermetic CI, and a quality system for a large team
- 22.8 · Swift Testing in depth: arguments, traits, errors, confirmations, isolation and scoping
- 22.9 · XCTest lifecycle and expectations, Sendable doubles, and the main actor in tests