| description | Swift Testing conventions, test structure, coverage rules, and DevColorExtraction specifics |
|---|---|
| read-when | Writing or reviewing a test, choosing what to run, or deciding what needs a fixture |
How to write and maintain tests in DevColorExtraction.
Run swift test, or the DevColorExtraction test plan in Xcode, which also reports
coverage.
IMPORTANT: This project uses Swift Testing, not XCTest. Don’t apply XCTest patterns or conventions.
- Use the
@Testattribute instead of function name conventions. - Use
#expect()and#require()instead ofXCTAssert*()functions. - Use
#expect(throws:)for error conditions. - Organize tests in structs, not classes.
- No “test” prefixes. Use descriptive names like
initialLoadingState(). - Name test types after the concrete type. For a protocol with a concrete implementation,
name the tests after the implementation, such as
MostCommonColorsTests.
Unit tests have three parts: set up, exercise, and expect.
- Set up: Create the inputs or mocks needed to exercise the unit under test.
- Exercise: Exercise the unit under test, usually by calling a function with the inputs from setup.
- Expect: Expect one or more results, using Swift Testing expressions.
Rules for these sections:
- Each test has exactly one unit under test. Only its invocation gets an
// exercisecomment. Other calls during setup or verification use// set upor// expectcomments. - Mark the start of each section with a comment, such as
// set up the test by creating a collection with two itemsor// expect that the item order is unchanged. If two sections overlap, mention only the more relevant one. - Every test has
// set upunless there’s genuinely nothing to set up. - Every test has
// expect. // exerciseis required when a distinct line triggers the behavior under test. Omit it only when the action and the assertion are the same expression.- Sections can repeat when useful, such as two
// set upblocks for different dependencies. - Comments are prose without colons:
// set up the test by creating a mock loader, not// set up:or// set up: mock loader. - Occasional unstructured comments, like
// unblock and wait for completion, are fine when they help.
- Test files are named
[TypeName]Tests.swift, one per type. - Test folders mirror source folders. Tests for
Sources/DevColorExtraction/go inTests/DevColorExtractionTests/. - Shared fixtures and helpers go in the test target’s
Resources/folder. - Group tests by function, each group preceded by a
// MARK: - [FunctionName]comment. - Imports:
@testable importthe module under test; import testing frameworks normally; import only what’s needed.
- Don’t test pure protocols that have no implementation.
- Every function and getter has at least one test.
- Add tests for edge cases and error conditions, and test both success and failure for throwing functions.
A test that uses #expect(throws:) must be marked throws, or the compiler reports “Errors
thrown from here are not handled.”
@Test
func decodingRejectsUnknownKind() throws {
#expect(throws: DecodingError.self) {
try decoder.decode(Kind.self, from: data)
}
}
Don’t compare Booleans to true or false. Use the value directly or negate it. Optional
Booleans are the exception, because the comparison unwraps them.
// ✅ Good
#expect(item.isEnabled)
#expect(!item.isEnabled)
#expect(response.isCached == true) // isCached is Bool?
// ❌ Bad
#expect(item.isEnabled == true)
Never force-unwrap optionals in tests. A nil crashes the test process instead of failing
cleanly. Optional chaining is also wrong, because it silently skips the expectation when the value
is nil.
// ✅ Good
let owner = try #require(item.owner)
#expect(owner.name == "Alice")
// ❌ Bad: crashes if nil
#expect(item.owner!.name == "Alice")
// ❌ Bad: passes if nil
#expect(item.owner?.name == "Alice")
This applies to any optional access, including dictionary lookups, first and last, and as?
casts. Prefer #require to guard let in test bodies.
Never subscript an array based on an earlier #expect of its count. If the expectation fails, the
test keeps going and the subscript crashes.
// ✅ Good
try #require(items.count == 2)
#expect(items[0].name == "first")
// ✅ Better
let first = try #require(items.first)
#expect(first.name == "first")
// ✅ Best: no positional access
#expect(items.map(\.name) == ["first", "second"])
When a path should never be reached in a passing test, use Issue.record(_:) with a descriptive
message, then return, because recording an issue doesn’t stop the test:
guard case .success(let value) = result else {
Issue.record("Expected .success, got \(result)")
return
}
Mark test structs and functions @MainActor when testing main-actor-isolated code, such as view
models.
When most tests in a struct need the same inputs or mocks, create them in the struct’s init.
Each test then shows only what makes it different.
When several tests build similar objects, extract a private helper with clear parameter defaults.
Shared setup covers the common baseline. Anything specific to one scenario goes in that test’s
// set up section, so readers don’t have to look elsewhere for context.
Tests extract colors from small images committed in
Tests/DevColorExtractionTests/Resources/ and declared as test resources. Each
fixture is drawn with known colors, which its name describes, such as
Dominant-White-90-Black-10.png.