A pull request moved caching out of FeedLoader into a shared layer. Every screen behaved exactly as before. CI went red anyway: eleven tests failed, because they asserted the old sequence of cache and API calls. The team spent an afternoon rewriting assertions for behavior they had deliberately preserved, and then merged a refactor that the tests had, in effect, voted against.
Nothing was wrong with the code. The tests were faithful to the wrong thing. They recorded how the loader worked, not what anyone depended on.
There is one question to ask of every assertion: who loses what if this fails? If the answer is “the next person who refactors,” the test is guarding the implementation. If the answer is “a reader on a train loses the feed they last saw,” the test is guarding a promise.
The test that records the wiring
import Foundation
import Testing
protocol FeedAPI: Sendable {
func latest() async throws -> [String]
}
final class RecordingAPI: FeedAPI, @unchecked Sendable {
var calls: [String] = []
func latest() async throws -> [String] {
calls.append("latest")
throw URLError(.notConnectedToInternet)
}
}A test built on this asserts calls == ["cache.read", "latest", "cache.write"]. It passes today, documents nothing a user can observe, and fails the moment someone reorders two lines for a good reason. The @unchecked Sendable is a second warning: the fake is shared mutable state, which will matter as soon as the tests run in parallel.
Test the outcome at the boundary the caller sees
struct FeedLoader: Sendable {
let api: any FeedAPI
let cached: [String]?
func load() async throws -> [String] {
do {
return try await api.latest()
} catch let error as URLError
where error.code == .notConnectedToInternet {
guard let cached else { throw error }
return cached
}
}
}
struct OfflineAPI: FeedAPI {
func latest() async throws -> [String] {
throw URLError(.notConnectedToInternet)
}
}
struct ServingAPI: FeedAPI {
let articles: [String]
func latest() async throws -> [String] { articles }
}
@Test("Offline, the reader keeps the last feed they saw")
func offlineShowsLastKnownFeed() async throws {
let loader = FeedLoader(api: OfflineAPI(), cached: ["Issue 16"])
#expect(try await loader.load() == ["Issue 16"])
}
@Test("Offline with nothing cached, the reader gets a recoverable error")
func offlineWithoutCacheThrows() async {
let loader = FeedLoader(api: OfflineAPI(), cached: nil)
await #expect(throws: URLError.self) { try await loader.load() }
}
@Test("An empty feed is a result, not a failure")
func emptyFeedIsSuccess() async throws {
let loader = FeedLoader(api: ServingAPI(articles: []), cached: ["Issue 16"])
#expect(try await loader.load() == [])
}Three tests, three decisions a user can see. None mentions how the cache is stored, when it is read, or in what order. The refactor that broke eleven tests breaks none of these, and a refactor that actually loses the offline feed breaks the first one, with a name that says what was lost.
The display name is part of the assertion. When it fails in CI, “Offline, the reader keeps the last feed they saw” tells the person on call what promise was broken before they open the file.
Call counts still matter when the interaction itself is the contract. One token refresh for three concurrent requests is visible to the authentication server. One credit per consumable purchase is visible to the buyer. Then count, at that boundary, and name the test for the effect: “three callers share one refresh,” not “refresh called once.”
Let parallel execution expose shared state
Swift Testing runs tests in parallel by default. Treat that less as a performance feature to switch off when it hurts and more as a free detector of hidden coupling. Two tests that pass alone and fail together share something: a singleton, a UserDefaults.standard key, a file in a fixed directory, a static cache.
Give each test what it needs, fresh: its own store, a unique temporary directory, its own preferences suite, an injected clock for anything that expires. A new suite instance per test does not help if the code under test still reaches for a global. .serialized exists for the rare suite that genuinely shares an external resource. Reaching for it to make a flaky suite pass is hiding the coupling it just found.
Let a table state the policy
When the behavior is a policy over a few dimensions, the test should read like the policy:
enum Connection: Sendable { case online, offline }
struct CachePolicyCase: Sendable, CustomTestStringConvertible {
let connection: Connection
let cached: [String]?
let expected: [String]? // nil means an error
var testDescription: String {
"\(connection), cache \(cached == nil ? "empty" : "present")"
}
}
@Test("Cache policy", arguments: [
CachePolicyCase(connection: .online, cached: ["Old"], expected: ["New"]),
CachePolicyCase(connection: .offline, cached: ["Old"], expected: ["Old"]),
CachePolicyCase(connection: .offline, cached: nil, expected: nil),
])
func cachePolicy(_ row: CachePolicyCase) async throws {
let api: any FeedAPI = row.connection == .online
? ServingAPI(articles: ["New"]) : OfflineAPI()
let loader = FeedLoader(api: api, cached: row.cached)
if let expected = row.expected {
#expect(try await loader.load() == expected)
} else {
await #expect(throws: URLError.self) { try await loader.load() }
}
}Each row runs as its own case, in parallel, and reports by its description. Choose rows that produce different outcomes. Adding every combination that exercises the same rule makes the table longer and the policy harder to read.
Make waiting explicit
A confirmation checks that an event happens while its body runs. The body has to stay alive until the event can happen:
protocol FeedObserver: Sendable {
func feedDidRefresh()
}
struct RefreshingLoader: Sendable {
let loader: FeedLoader
let observer: any FeedObserver
func refresh() async throws {
_ = try await loader.load()
observer.feedDidRefresh()
}
}
struct CallbackObserver: FeedObserver {
let onRefresh: @Sendable () -> Void
func feedDidRefresh() { onRefresh() }
}
@Test("A refresh notifies the observer exactly once")
func refreshNotifiesOnce() async throws {
try await confirmation(expectedCount: 1) { refreshed in
let observer = CallbackObserver { refreshed() }
let loader = RefreshingLoader(
loader: FeedLoader(api: ServingAPI(articles: ["A"]), cached: nil),
observer: observer)
try await loader.refresh()
}
}The body awaits the refresh, so the confirmation sees the callback. If the work were started in an unstructured task and the body returned immediately, the confirmation would fail, correctly, because nothing in the test waited for the event. Adding Task.sleep would make it pass most of the time, which is worse than failing every time: it gives the scheduler more chances without stating which ordering the test needs.
Make the failure explain the loss
Two more tools keep failures honest.
withKnownIssue marks a test whose failure is understood and tracked. It belongs next to a ticket and the specific assertion, so the suite stays green without lying, and it starts reporting the moment the bug is fixed.
Exit tests, #expect(processExitsWith:), verify that a documented precondition really terminates the process, on hosts that support them such as macOS. Use them for invariants that genuinely should crash. For a corrupt document a customer opens, the behavior worth testing is usually the opposite: a recoverable error, and a library left intact. Test that with a corrupt fixture.
What to ask of your own tests
- For each assertion, who would lose what if it failed?
- Would a behavior-preserving refactor break this test?
- Does the test name describe the promise, so a failure explains itself?
- Do the tests pass in parallel, in any order, with fresh fixtures?
- Is anything waiting by sleeping instead of by awaiting the event?
A test suite earns its keep on the day the implementation changes. If that is the day it fails, it was testing the wrong thing.
References
- Swift Testing
- Implementing parameterized tests
- Confirming that an event occurs
- Known issues
- Exit testing
Related editions
- Edition 21 · Your Protocol Is Not an Architecture
- Edition 22 · When Actors Are Not Enough: Reentrancy and State Ownership
- Edition 33 · Your Debugging Session Should Survive an Interruption
If this edition sharpened your next review, you can buy me a coffee.