Approach: F.I.R.S.T-First, Production-Ready Tests -- Every test produced by this skill must be Fast, Isolated, Repeatable, Self-validating, and Thorough. Architecture changes to production code and improvements to the test suite both follow phased, low-risk PRs tracked in a refactoring/ directory.
iOS Swift Testing
Enterprise-grade testing skill covering 11 areas across all iOS architectures. Opinionated: prescribes Swift Testing (@Test/@Suite/#expect) for all new tests on Xcode 16+, protocol-based mocks with call tracking, F.I.R.S.T compliance checks on every generated test, and architecture-specific patterns for MVVM (UIKit+Combine, SwiftUI+@Observable), VIPER, and TCA.
Test Distribution Rule
Target: 90% unit tests (mocked, milliseconds) | 8% integration (real DB/network stub) | 2% UI (XCUITest). When in doubt, write a unit test.
F.I.R.S.T Principles
| Principle |
What it means |
Violation signal |
| Fast |
Unit tests should run in milliseconds. Avoid unnecessary waits. |
Real URLSession, Thread.sleep, disk I/O |
| Isolated |
Tests don't share state. Order doesn't matter. |
static var, setUp skipped, test A breaks B |
| Repeatable |
Same result on any machine, any time. |
Date(), UUID(), random data, time zones |
| Self-validating |
Pass or fail -- no log inspection. |
print(result) with no assertion |
| Thorough |
Happy path + error path + edge cases. |
Only green-path tests, 0% error coverage |
Quick Decision Trees
"Swift Testing or XCTest?"
Need UI testing? -> XCTest (XCUITest) only
Need performance testing? -> XCTest (measure {}) only
Need attachments? -> XCTest only
Need ObjC support? -> XCTest only
New unit/integration test? -> Swift Testing (preferred)
Existing XCTest? -> Migrate incrementally, both coexist
"Which assertion macro?"
Soft check (report + continue)? -> #expect(expr)
Hard precondition (halt on fail)? -> try #require(expr)
Unwrap optional + use value? -> let val = try #require(optional)
Check error thrown? -> #expect(throws: Type.self) { }
Check nothing thrown? -> #expect(throws: Never.self) { }
Record unconditional failure? -> Issue.record("msg")
"How to test async code?"
@Published + Combine (XCTest)?
-> dropFirst() + expectation + sink + waitForExpectations
@Observable (XCTest)?
-> withObservationTracking + expectation + waitForExpectations
@Observable sync?
-> direct assertion, no waiting needed
Swift Testing + async?
-> confirmation() for event counting
-> withCheckedContinuation for completion handlers
-> for await in stream.prefix(N) for AsyncStream
TCA?
-> TestStore + await send/receive + TestClock
ViewModel with internal Task {}?
-> expectation/confirmation or withMainSerialExecutor
"Mock, Stub, or Spy?"
Need to verify method WAS CALLED? -> Spy/Mock (tracks calls)
Need to provide CANNED RESPONSE? -> Stub (returns fixed data)
Need BOTH? -> Mock = Stub + Spy
System singleton? -> Protocol wrapper + inject
1-2 dependency methods? -> Closure-based injection
3+ methods or call counting? -> Protocol-based injection
VIPER protocols (many modules)? -> Sourcery AutoMockable
"Which architecture testing pattern?"
MVVM + SwiftUI + @Observable?
-> references/observable-testing.md + references/async-testing.md
MVVM + UIKit + Combine?
-> references/xctest-patterns.md (Combine section)
VIPER / Clean Architecture?
-> references/viper-testing.md
TCA (Composable Architecture)?
-> references/tca-testing.md
UI Testing?
-> references/ui-testing.md
Snapshot Testing?
-> references/snapshot-testing.md
Workflows
Workflow: Write a New Test Suite
When: Adding tests for a new or untested component.
- Identify the component's protocol (or create one if missing)
- Create the mock: implement protocol with
stubbed* returns and *CallCount tracking
- Write test type:
@MainActor struct ViewModelTests (Swift Testing) or @MainActor final class ... : XCTestCase
- Write the Arrange block: create mock + inject into SUT
- Write at minimum: success case, error case, edge/empty case
- Add memory leak detection (
references/enterprise-testing.md)
- Run the suite -- all tests must be green before committing
Workflow: Migrate XCTest Suite to Swift Testing
When: Modernizing a legacy test suite on Xcode 16+. Never in same PR as production changes.
- Read
references/refactoring-workflow.md -- create migration plan in refactoring/
- Migrate one test file at a time (<=200 lines per PR)
- Apply mechanical transforms: assertion mapping table in
references/refactoring-workflow.md
- DANGER: Check for third-party libraries using XCTAssert under the hood (
references/anti-patterns.md C5/C6/C7)
- Replace
setUp/tearDown with stored properties or init
- Add
@Suite("ComponentName") and descriptive @Test("does X when Y") names
- Mark
@MainActor on @Suite type when testing isolated ViewModels
- Run full suite -- if flaky under parallel execution, add
@Suite(.serialized) + log task
- Update
refactoring/ plan
Workflow: Audit Existing Test Suite
When: First encounter with a legacy test suite, or preparing a quality report.
- Scan for anti-patterns using
references/anti-patterns.md detection checklist and grep script
- Check for framework mixing (C5/C6/C7). When you find C6 (
#expect in XCTestCase), also check M6: is the #expect argument a pre-evaluated Bool variable (e.g. let isValid = ...; #expect(isValid))? These are separate issues — M6 persists even after the context is fixed. Always report both.
- Check for
wait(for:) deadlocks, real network calls, shared statics
- Measure test pyramid ratio: count unit vs integration vs UI tests
- Identify untested ViewModels: grep for
class.*ViewModel without corresponding *Tests file
- Create
refactoring/test-debt.md with severity-ranked findings
- Fix Critical (deadlocks, crashes, silent passes) first
Workflow: Test Architecture-Specific Code
When: Testing VIPER modules, TCA features, or specific architecture patterns.
- Identify architecture: MVVM (UIKit/SwiftUI), VIPER, TCA, or other
- Read the corresponding reference file for patterns
- For VIPER: test Presenter (mock View + Interactor), Interactor (mock Services), Router (spy NavController) (
references/viper-testing.md)
- For TCA: use TestStore with
@MainActor, override dependencies, assert exhaustively (references/tca-testing.md)
- For @Observable MVVM: use
withObservationTracking or direct sync assertions (references/observable-testing.md)
- For UIKit+Combine MVVM: use
dropFirst() + sink + scheduler injection (references/xctest-patterns.md)
Code Generation Rules
- Use Swift Testing (
@Test/@Suite/#expect) for new tests -- XCTest only when Xcode 15 or older, or UI/performance testing
- One concept per test function -- no
and in test names
- Mock all external dependencies via protocols -- never use real URLSession, CoreData, or FileManager in unit tests
- Mark test type
@MainActor when SUT is @MainActor-isolated
- Add memory leak detection to every ViewModel test
- Use
try #require() before unwrapping optionals in test setup
- Use test data factories (
Item.sample()) not raw initializers
- Cover at minimum: success, failure, and empty/edge case
- Set
.timeLimit(.minutes(1)) on any test that touches async code
- Put expressions inside
#expect() -- never pre-evaluate to Bool
- NEVER use XCTAssert* in @Test functions or #expect in XCTestCase -- silently swallowed
- For TCA: mutate
$0 in send/receive closures, never use XCTAssertEqual; use case key paths for receive
- For @Observable: use withObservationTracking for async changes, direct assertion for sync
- For Combine: always dropFirst(), subscribe BEFORE action, capture value from sink (willSet semantics)
- Before generating tests, output a brief
<thought> identifying: what public behaviors to test, what dependencies to mock, which architecture pattern applies, and which F.I.R.S.T principle is most at risk
- When diagnosing a test failure or identifying a testing anti-pattern, always attach an explicit severity label (🔴 Critical / 🟡 High / 🟢 Medium) before explaining the fix. Severity frames urgency for code review — "hangs forever because
wait(for:) cannot pump the main queue inside an async function" is a 🔴 Critical issue, not a "hmm, worth looking at". Without an explicit label, reviewers can't triage and the finding gets deferred.
Severity Levels for Testing Anti-Patterns
Use this table to classify any test issue you surface — during generation, diagnosis, or review.
| Severity |
Meaning |
Examples |
| 🔴 Critical |
Test hangs, crashes, or lies — produces wrong signal |
wait(for:) inside async (hang), XCTAssert* inside @Test (silently swallowed), #expect inside XCTestCase (no-op), real URLSession in unit test (flaky + slow), shared mutable static var state between tests |
| 🟡 High |
Test runs but breaks F.I.R.S.T or gives false confidence |
Missing @MainActor on @MainActor-isolated SUT, no await fulfillment(of:) for async (timeout race), missing dropFirst() on Combine, no memory leak detection on ViewModel, testing only the happy path |
| 🟢 Medium |
Functional but fragile or hard to maintain |
Raw initializers instead of test data factories, and in test names, over-mocked boundary, mock over 100 lines, setUp/tearDown doing unrelated work |
How to apply: When answering "why does my test X?" or "what's wrong with this test code?", the response must lead with 🔴 Critical — <short label> (or High/Medium) before the explanation. If the cause is a hanging async test, it's Critical. If it's a missing @MainActor, it's High. Never omit the label.
Fallback Strategies & Loop Breakers
- @MainActor isolation compile errors in tests: Add
@MainActor to the entire test type declaration -- not just the method. Why: Swift Testing infers isolation from the type, not individual methods. If error persists, wrap assertions in await MainActor.run { } as last resort.
- Flaky test under Swift Testing parallel execution: Add
@Suite(.serialized). Log a task in refactoring/ to investigate. Why: Swift Testing runs all tests in ONE PROCESS with cooperative concurrency (unlike XCTest which used separate processes), so shared mutable state causes non-deterministic failures.
- Mock grows beyond 100 lines: Split into focused mocks that implement protocol subsets. Large mocks are a signal that the protocol itself violates Interface Segregation.
- Can't inject dependency (no protocol, no constructor injection): Add the protocol in a separate PR first. Why: mixing dependency extraction with test writing creates large, hard-to-review PRs.
- Third-party library uses XCTAssert under the hood: Keep those tests as XCTestCase until library adds Swift Testing support. Why: XCTAssert silently becomes a no-op inside
@Test functions -- tests pass even when assertions fail.
- TCA TestStore failures don't fail @Test: Ensure TCA >= 1.12. Why: earlier versions used XCTFail internally, which is silently swallowed in
@Test context.
- confirmation() fails with completion-handler APIs: Use
withCheckedContinuation to bridge. Why: confirmation() checks the count when its closure returns, not when a callback fires later.
Confidence Checks
Before finalizing generated or reviewed tests, verify ALL:
[] F.I.R.S.T compliant -- no real network, no shared state, no Date()/UUID(), has assertion, covers error paths
[] Correct framework -- Swift Testing for new code (Xcode 16+), no framework mixing within a function
[] One concept per test -- no "and" in test name, no multiple unrelated assertions
[] Mock protocol-based -- no concrete type dependencies, no URLSession in unit tests
[] @MainActor -- present on test type when SUT is @MainActor
[] Memory leak detection -- addTeardownBlock or makeSUT pattern present
[] Async safety -- await fulfillment(of:) not wait(for:), timeLimit set
[] Test data factory -- Item.sample() pattern, not raw initializers
[] Error path coverage -- at least one test for the failure case
[] Naming -- "test_<method>_<condition>_<expected>" or @Test("does X when Y")
[] No framework mixing -- no XCTAssert in @Test, no #expect in XCTestCase
[] Architecture-specific -- correct patterns for MVVM/VIPER/TCA
Companion Skills
| Test context |
Companion skill |
When |
Testing @Observable / @MainActor ViewModels |
swiftui-mvvm skill |
ViewModel structure, ViewState enum |
| Testing UIKit + Combine ViewModels |
uikit-mvvm skill |
Combine publisher testing, Coordinator testing |
| Testing async/await and actor-isolated code |
swift-concurrency skill |
withMainSerialExecutor, Clock injection |
| Testing code with GCD/OperationQueue |
gcd-operations skill |
Dispatch queue mocking |
References
| Reference |
When to Read |
references/rules.md |
Do's and Don'ts quick reference: priority rules and critical anti-patterns |
references/swift-testing-framework.md |
@Test, @Suite, #expect, #require, parameterized tests, tags, confirmation(), known issues, coexistence dangers, parallel execution, traits |
references/xctest-patterns.md |
XCTestCase structure, mock pattern, memory leak detection, Combine @Published testing, scheduler injection, coordinator testing |
references/async-testing.md |
withMainSerialExecutor, await fulfillment, Clock injection, AsyncStream testing, confirmation() semantics, timeout patterns |
references/observable-testing.md |
withObservationTracking, willSet semantics, sync vs async @Observable testing, NavigationPath, sheet/cover state |
references/viper-testing.md |
Presenter/Interactor/Router testing, weak reference enforcement, module assembly, entity boundaries, mock management |
references/tca-testing.md |
TestStore, exhaustive assertions, receive() case key paths, TestClock, dependencies, navigation, @Shared state |
references/ui-testing.md |
Page Object Model, waitForExistence, system alerts, launch arguments, deep link testing, screenshots, accessibility audit |
references/snapshot-testing.md |
Device pinning, recording modes, CI configuration, SwiftUI hosting, precision settings, multi-strategy |
references/integration-testing.md |
URLProtocol mocking, Core Data /dev/null, SwiftData, Keychain protocol wrapper, UserDefaults isolation, system services |
references/enterprise-testing.md |
OAuth token refresh, feature flags, analytics spies, deep linking, push notifications, memory leak detection, test data builders, accessibility |
references/anti-patterns.md |
Detection checklist with grep patterns, severity-ranked (Critical/High/Medium), framework mixing dangers |
references/test-organization.md |
File structure, naming, Test Plans, CI configuration, parallel testing, coverage targets, flaky test quarantine, time budgets |
references/refactoring-workflow.md |
Complete assertion mapping table, lifecycle mapping, migration plan, PR sizing, coexistence rules, common mistakes |
1---2name: ios-testing3description: "Invoke any time a user is writing iOS/Swift tests or asking why tests behave a certain way — including XCTest versus Swift Testing (@Test/#expect) choices, async ViewModel tests with @Observable or @Published, snapshot testing across device sizes, mocking protocols for dependency injection, setUp/tearDown lifecycle issues, tests that fail on CI but pass locally, flaky async tests, testing VIPER/TCA/MVVM architectures, and coverage gaps on error paths. The trigger is user intent: they are trying to verify, assert, or validate iOS/Swift behavior in a test context, whether they use the word 'testing' or not."4metadata:5 source: https://skillmd.com/skills/aibot88/ios-testing6 version: 2.1.37---89> **Approach: F.I.R.S.T-First, Production-Ready Tests** -- Every test produced by this skill must be Fast, Isolated, Repeatable, Self-validating, and Thorough. Architecture changes to production code and improvements to the test suite both follow phased, low-risk PRs tracked in a `refactoring/` directory.1011# iOS Swift Testing1213Enterprise-grade testing skill covering 11 areas across all iOS architectures. Opinionated: prescribes Swift Testing (`@Test`/`@Suite`/`#expect`) for all new tests on Xcode 16+, protocol-based mocks with call tracking, F.I.R.S.T compliance checks on every generated test, and architecture-specific patterns for MVVM (UIKit+Combine, SwiftUI+@Observable), VIPER, and TCA.1415## Test Distribution Rule1617Target: 90% unit tests (mocked, milliseconds) | 8% integration (real DB/network stub) | 2% UI (XCUITest). When in doubt, write a unit test.1819## F.I.R.S.T Principles2021| Principle | What it means | Violation signal |22|-----------|--------------|-----------------|23| **F**ast | Unit tests should run in milliseconds. Avoid unnecessary waits. | Real `URLSession`, `Thread.sleep`, disk I/O |24| **I**solated | Tests don't share state. Order doesn't matter. | `static var`, `setUp` skipped, test A breaks B |25| **R**epeatable | Same result on any machine, any time. | `Date()`, `UUID()`, random data, time zones |26| **S**elf-validating | Pass or fail -- no log inspection. | `print(result)` with no assertion |27| **T**horough | Happy path + error path + edge cases. | Only green-path tests, 0% error coverage |2829## Quick Decision Trees3031### "Swift Testing or XCTest?"3233```text34Need UI testing? -> XCTest (XCUITest) only35Need performance testing? -> XCTest (measure {}) only36Need attachments? -> XCTest only37Need ObjC support? -> XCTest only38New unit/integration test? -> Swift Testing (preferred)39Existing XCTest? -> Migrate incrementally, both coexist40```4142### "Which assertion macro?"4344```text45Soft check (report + continue)? -> #expect(expr)46Hard precondition (halt on fail)? -> try #require(expr)47Unwrap optional + use value? -> let val = try #require(optional)48Check error thrown? -> #expect(throws: Type.self) { }49Check nothing thrown? -> #expect(throws: Never.self) { }50Record unconditional failure? -> Issue.record("msg")51```5253### "How to test async code?"5455```text56@Published + Combine (XCTest)?57 -> dropFirst() + expectation + sink + waitForExpectations5859@Observable (XCTest)?60 -> withObservationTracking + expectation + waitForExpectations6162@Observable sync?63 -> direct assertion, no waiting needed6465Swift Testing + async?66 -> confirmation() for event counting67 -> withCheckedContinuation for completion handlers68 -> for await in stream.prefix(N) for AsyncStream6970TCA?71 -> TestStore + await send/receive + TestClock7273ViewModel with internal Task {}?74 -> expectation/confirmation or withMainSerialExecutor75```7677### "Mock, Stub, or Spy?"7879```text80Need to verify method WAS CALLED? -> Spy/Mock (tracks calls)81Need to provide CANNED RESPONSE? -> Stub (returns fixed data)82Need BOTH? -> Mock = Stub + Spy83System singleton? -> Protocol wrapper + inject841-2 dependency methods? -> Closure-based injection853+ methods or call counting? -> Protocol-based injection86VIPER protocols (many modules)? -> Sourcery AutoMockable87```8889### "Which architecture testing pattern?"9091```text92MVVM + SwiftUI + @Observable?93 -> references/observable-testing.md + references/async-testing.md9495MVVM + UIKit + Combine?96 -> references/xctest-patterns.md (Combine section)9798VIPER / Clean Architecture?99 -> references/viper-testing.md100101TCA (Composable Architecture)?102 -> references/tca-testing.md103104UI Testing?105 -> references/ui-testing.md106107Snapshot Testing?108 -> references/snapshot-testing.md109```110111## Workflows112113### Workflow: Write a New Test Suite114115**When:** Adding tests for a new or untested component.1161171. Identify the component's protocol (or create one if missing)1182. Create the mock: implement protocol with `stubbed*` returns and `*CallCount` tracking1193. Write test type: `@MainActor struct ViewModelTests` (Swift Testing) or `@MainActor final class ... : XCTestCase`1204. Write the Arrange block: create mock + inject into SUT1215. Write at minimum: success case, error case, edge/empty case1226. Add memory leak detection (`references/enterprise-testing.md`)1237. Run the suite -- all tests must be green before committing124125### Workflow: Migrate XCTest Suite to Swift Testing126127**When:** Modernizing a legacy test suite on Xcode 16+. Never in same PR as production changes.1281291. Read `references/refactoring-workflow.md` -- create migration plan in `refactoring/`1302. Migrate one test file at a time (<=200 lines per PR)1313. Apply mechanical transforms: assertion mapping table in `references/refactoring-workflow.md`1324. DANGER: Check for third-party libraries using XCTAssert under the hood (`references/anti-patterns.md` C5/C6/C7)1335. Replace `setUp`/`tearDown` with stored properties or `init`1346. Add `@Suite("ComponentName")` and descriptive `@Test("does X when Y")` names1357. Mark `@MainActor` on `@Suite` type when testing isolated ViewModels1368. Run full suite -- if flaky under parallel execution, add `@Suite(.serialized)` + log task1379. Update `refactoring/` plan138139### Workflow: Audit Existing Test Suite140141**When:** First encounter with a legacy test suite, or preparing a quality report.1421431. Scan for anti-patterns using `references/anti-patterns.md` detection checklist and grep script1442. Check for framework mixing (C5/C6/C7). When you find C6 (`#expect` in XCTestCase), **also check M6**: is the `#expect` argument a pre-evaluated Bool variable (e.g. `let isValid = ...; #expect(isValid)`)? These are separate issues — M6 persists even after the context is fixed. Always report both.1453. Check for `wait(for:)` deadlocks, real network calls, shared statics1464. Measure test pyramid ratio: count unit vs integration vs UI tests1475. Identify untested ViewModels: grep for `class.*ViewModel` without corresponding `*Tests` file1486. Create `refactoring/test-debt.md` with severity-ranked findings1497. Fix Critical (deadlocks, crashes, silent passes) first150151### Workflow: Test Architecture-Specific Code152153**When:** Testing VIPER modules, TCA features, or specific architecture patterns.1541551. Identify architecture: MVVM (UIKit/SwiftUI), VIPER, TCA, or other1562. Read the corresponding reference file for patterns1573. For VIPER: test Presenter (mock View + Interactor), Interactor (mock Services), Router (spy NavController) (`references/viper-testing.md`)1584. For TCA: use TestStore with `@MainActor`, override dependencies, assert exhaustively (`references/tca-testing.md`)1595. For @Observable MVVM: use `withObservationTracking` or direct sync assertions (`references/observable-testing.md`)1606. For UIKit+Combine MVVM: use `dropFirst()` + sink + scheduler injection (`references/xctest-patterns.md`)161162## Code Generation Rules163164<critical_rules>165When generating or reviewing tests, every output must be **F.I.R.S.T-compliant, production-ready, and PR-shippable**. ALWAYS:1661671. Use Swift Testing (`@Test`/`@Suite`/`#expect`) for new tests -- XCTest only when Xcode 15 or older, or UI/performance testing1682. One concept per test function -- no `and` in test names1693. Mock all external dependencies via protocols -- never use real URLSession, CoreData, or FileManager in unit tests1704. Mark test type `@MainActor` when SUT is `@MainActor`-isolated1715. Add memory leak detection to every ViewModel test1726. Use `try #require()` before unwrapping optionals in test setup1737. Use test data factories (`Item.sample()`) not raw initializers1748. Cover at minimum: success, failure, and empty/edge case1759. Set `.timeLimit(.minutes(1))` on any test that touches async code17610. Put expressions inside `#expect()` -- never pre-evaluate to Bool17711. NEVER use XCTAssert* in @Test functions or #expect in XCTestCase -- silently swallowed17812. For TCA: mutate `$0` in send/receive closures, never use XCTAssertEqual; use case key paths for receive17913. For @Observable: use withObservationTracking for async changes, direct assertion for sync18014. For Combine: always dropFirst(), subscribe BEFORE action, capture value from sink (willSet semantics)18115. Before generating tests, output a brief `<thought>` identifying: what public behaviors to test, what dependencies to mock, which architecture pattern applies, and which F.I.R.S.T principle is most at risk18216. **When diagnosing a test failure or identifying a testing anti-pattern, always attach an explicit severity label** (🔴 Critical / 🟡 High / 🟢 Medium) before explaining the fix. Severity frames urgency for code review — "hangs forever because `wait(for:)` cannot pump the main queue inside an `async` function" is a **🔴 Critical** issue, not a "hmm, worth looking at". Without an explicit label, reviewers can't triage and the finding gets deferred.183</critical_rules>184185## Severity Levels for Testing Anti-Patterns186187Use this table to classify any test issue you surface — during generation, diagnosis, or review.188189| Severity | Meaning | Examples |190|:--------:|---------|----------|191| 🔴 **Critical** | Test hangs, crashes, or lies — produces wrong signal | `wait(for:)` inside `async` (hang), `XCTAssert*` inside `@Test` (silently swallowed), `#expect` inside `XCTestCase` (no-op), real `URLSession` in unit test (flaky + slow), shared mutable `static var` state between tests |192| 🟡 **High** | Test runs but breaks F.I.R.S.T or gives false confidence | Missing `@MainActor` on `@MainActor`-isolated SUT, no `await fulfillment(of:)` for async (timeout race), missing `dropFirst()` on Combine, no memory leak detection on ViewModel, testing only the happy path |193| 🟢 **Medium** | Functional but fragile or hard to maintain | Raw initializers instead of test data factories, `and` in test names, over-mocked boundary, mock over 100 lines, `setUp`/`tearDown` doing unrelated work |194195**How to apply:** When answering "why does my test X?" or "what's wrong with this test code?", the response must lead with `🔴 Critical — <short label>` (or High/Medium) before the explanation. If the cause is a hanging async test, it's Critical. If it's a missing `@MainActor`, it's High. Never omit the label.196197## Fallback Strategies & Loop Breakers198199<fallback_strategies>200When migrating or writing tests, you may hit stubborn issues. If the same problem appears twice, break the loop:2012021. **@MainActor isolation compile errors in tests**: Add `@MainActor` to the entire test type declaration -- not just the method. Why: Swift Testing infers isolation from the type, not individual methods. If error persists, wrap assertions in `await MainActor.run { }` as last resort.2032. **Flaky test under Swift Testing parallel execution**: Add `@Suite(.serialized)`. Log a task in `refactoring/` to investigate. Why: Swift Testing runs all tests in ONE PROCESS with cooperative concurrency (unlike XCTest which used separate processes), so shared mutable state causes non-deterministic failures.2043. **Mock grows beyond 100 lines**: Split into focused mocks that implement protocol subsets. Large mocks are a signal that the protocol itself violates Interface Segregation.2054. **Can't inject dependency** (no protocol, no constructor injection): Add the protocol in a separate PR first. Why: mixing dependency extraction with test writing creates large, hard-to-review PRs.2065. **Third-party library uses XCTAssert under the hood**: Keep those tests as XCTestCase until library adds Swift Testing support. Why: XCTAssert silently becomes a no-op inside `@Test` functions -- tests pass even when assertions fail.2076. **TCA TestStore failures don't fail @Test**: Ensure TCA >= 1.12. Why: earlier versions used XCTFail internally, which is silently swallowed in `@Test` context.2087. **confirmation() fails with completion-handler APIs**: Use `withCheckedContinuation` to bridge. Why: `confirmation()` checks the count when its closure *returns*, not when a callback fires later.209</fallback_strategies>210211## Confidence Checks212213Before finalizing generated or reviewed tests, verify ALL:214215```text216[] F.I.R.S.T compliant -- no real network, no shared state, no Date()/UUID(), has assertion, covers error paths217[] Correct framework -- Swift Testing for new code (Xcode 16+), no framework mixing within a function218[] One concept per test -- no "and" in test name, no multiple unrelated assertions219[] Mock protocol-based -- no concrete type dependencies, no URLSession in unit tests220[] @MainActor -- present on test type when SUT is @MainActor221[] Memory leak detection -- addTeardownBlock or makeSUT pattern present222[] Async safety -- await fulfillment(of:) not wait(for:), timeLimit set223[] Test data factory -- Item.sample() pattern, not raw initializers224[] Error path coverage -- at least one test for the failure case225[] Naming -- "test_<method>_<condition>_<expected>" or @Test("does X when Y")226[] No framework mixing -- no XCTAssert in @Test, no #expect in XCTestCase227[] Architecture-specific -- correct patterns for MVVM/VIPER/TCA228```229230## Companion Skills231232| Test context | Companion skill | When |233|---|---|---|234| Testing `@Observable` / `@MainActor` ViewModels | swiftui-mvvm skill | ViewModel structure, ViewState enum |235| Testing UIKit + Combine ViewModels | uikit-mvvm skill | Combine publisher testing, Coordinator testing |236| Testing async/await and actor-isolated code | swift-concurrency skill | `withMainSerialExecutor`, Clock injection |237| Testing code with GCD/OperationQueue | gcd-operations skill | Dispatch queue mocking |238239## References240241| Reference | When to Read |242|-----------|-------------|243| `references/rules.md` | Do's and Don'ts quick reference: priority rules and critical anti-patterns |244| `references/swift-testing-framework.md` | @Test, @Suite, #expect, #require, parameterized tests, tags, confirmation(), known issues, coexistence dangers, parallel execution, traits |245| `references/xctest-patterns.md` | XCTestCase structure, mock pattern, memory leak detection, Combine @Published testing, scheduler injection, coordinator testing |246| `references/async-testing.md` | withMainSerialExecutor, await fulfillment, Clock injection, AsyncStream testing, confirmation() semantics, timeout patterns |247| `references/observable-testing.md` | withObservationTracking, willSet semantics, sync vs async @Observable testing, NavigationPath, sheet/cover state |248| `references/viper-testing.md` | Presenter/Interactor/Router testing, weak reference enforcement, module assembly, entity boundaries, mock management |249| `references/tca-testing.md` | TestStore, exhaustive assertions, receive() case key paths, TestClock, dependencies, navigation, @Shared state |250| `references/ui-testing.md` | Page Object Model, waitForExistence, system alerts, launch arguments, deep link testing, screenshots, accessibility audit |251| `references/snapshot-testing.md` | Device pinning, recording modes, CI configuration, SwiftUI hosting, precision settings, multi-strategy |252| `references/integration-testing.md` | URLProtocol mocking, Core Data /dev/null, SwiftData, Keychain protocol wrapper, UserDefaults isolation, system services |253| `references/enterprise-testing.md` | OAuth token refresh, feature flags, analytics spies, deep linking, push notifications, memory leak detection, test data builders, accessibility |254| `references/anti-patterns.md` | Detection checklist with grep patterns, severity-ranked (Critical/High/Medium), framework mixing dangers |255| `references/test-organization.md` | File structure, naming, Test Plans, CI configuration, parallel testing, coverage targets, flaky test quarantine, time budgets |256| `references/refactoring-workflow.md` | Complete assertion mapping table, lifecycle mapping, migration plan, PR sizing, coexistence rules, common mistakes |