/ios-agent-skills:ios-testingfrom ios-agent-skills
Guides writing and debugging iOS/Swift tests across XCTest and Swift Testing, covering async ViewModels, mocking, snapshot tests, and architecture-specific patterns for MVVM, VIPER, and TCA.
Ships in ios-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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.
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.
Target: 90% unit tests (mocked, milliseconds) | 8% integration (real DB/network stub) | 2% UI (XCUITest). When in doubt, write a unit test.
| 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 |
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
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")
@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
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
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
When: Adding tests for a new or untested component.
stubbed* returns and *CallCount tracking@MainActor struct ViewModelTests (Swift Testing) or @MainActor final class ... : XCTestCasereferences/enterprise-testing.md)When: Modernizing a legacy test suite on Xcode 16+. Never in same PR as production changes.
references/refactoring-workflow.md -- create migration plan in refactoring/references/refactoring-workflow.mdreferences/anti-patterns.md C5/C6/C7)setUp/tearDown with stored properties or init@Suite("ComponentName") and descriptive @Test("does X when Y") names@MainActor on @Suite type when testing isolated ViewModels@Suite(.serialized) + log taskrefactoring/ planWhen: First encounter with a legacy test suite, or preparing a quality report.
references/anti-patterns.md detection checklist and grep script#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.wait(for:) deadlocks, real network calls, shared staticsclass.*ViewModel without corresponding *Tests filerefactoring/test-debt.md with severity-ranked findingsWhen: Testing VIPER modules, TCA features, or specific architecture patterns.
references/viper-testing.md)@MainActor, override dependencies, assert exhaustively (references/tca-testing.md)withObservationTracking or direct sync assertions (references/observable-testing.md)dropFirst() + sink + scheduler injection (references/xctest-patterns.md)<critical_rules> When generating or reviewing tests, every output must be F.I.R.S.T-compliant, production-ready, and PR-shippable. ALWAYS:
@Test/@Suite/#expect) for new tests -- XCTest only when Xcode 15 or older, or UI/performance testingand in test names@MainActor when SUT is @MainActor-isolatedtry #require() before unwrapping optionals in test setupItem.sample()) not raw initializers.timeLimit(.minutes(1)) on any test that touches async code#expect() -- never pre-evaluate to Bool$0 in send/receive closures, never use XCTAssertEqual; use case key paths for receive<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 riskwait(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.
</critical_rules>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> When migrating or writing tests, you may hit stubborn issues. If the same problem appears twice, break the loop:
@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.@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.@Test functions -- tests pass even when assertions fail.@Test context.withCheckedContinuation to bridge. Why: confirmation() checks the count when its closure returns, not when a callback fires later.
</fallback_strategies>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
| 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 |
| 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 |
README.md (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/async-testing.md (opens in a new tab)references/enterprise-testing.md (opens in a new tab)references/integration-testing.md (opens in a new tab)references/observable-testing.md (opens in a new tab)references/refactoring-workflow.md (opens in a new tab)references/rules.md (opens in a new tab)references/snapshot-testing.md (opens in a new tab)references/swift-testing-framework.md (opens in a new tab)references/tca-testing.md (opens in a new tab)references/test-organization.md (opens in a new tab)references/ui-testing.md (opens in a new tab)references/viper-testing.md (opens in a new tab)references/xctest-patterns.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
swift-testing, xctest, unit-testing, ui-testing, test-automation
Generated from the plugin's indexed repository (rusel95/ios-agent-skills) — no native marketplace selected
npx claudepluginhub p/rusel95-ios-agent-skills11 skills in this plugin
/gcd-operationsUse for iOS/macOS concurrency problems involving dispatch queues, locks, or thread safety. Triggers on: deadlocks (sync on main, nested sync, ABBA lock ordering), thread explosion from too many DispatchQueue.global() calls, data races flagged by Thread Sanitizer (TSan), DispatchGroup enter/leave imbalance, DispatchSource timer leaks, lock selection (NSLock vs OSAllocatedUnfairLock vs os_unfair_lock), reader-writer barriers, AsyncOperation subclasses, dispatchPrecondition usage, and OperationQueue throttling. Also use when migrating GCD patterns to Swift Concurrency actors. Apply whenever someone asks about thread-safe properties, concurrent access to shared state, or sees TSan warnings in Apple platform code — even if they don't say 'GCD' or 'concurrency.'/ios-accessibilityProduction-grade iOS accessibility skill covering VoiceOver, Dynamic Type, color contrast, motion, Switch Control, Voice Control, and WCAG 2.2 compliance for both SwiftUI and UIKit. This skill should be used when creating new iOS screens or views, reviewing existing iOS code for accessibility, adding VoiceOver support, fixing Dynamic Type issues, auditing WCAG compliance, implementing accessibilityLabel/traits/hints, grouping elements for assistive technology, adding custom actions or rotors, respecting system accessibility preferences (reduce motion, increase contrast, differentiate without color), writing accessibility-focused XCTest audits, or preparing apps for enterprise compliance (ADA, EAA, Section 508). Use this skill any time someone is working with iOS accessibility, VoiceOver, Dynamic Type, assistive technology, WCAG mapping, or accessibility modifiers in SwiftUI or UIKit — even if they only say 'make this accessible' or 'add VoiceOver support' or 'check contrast.' Also run an accessibility pass on any newly generated SwiftUI or UIKit view code before finalizing — AI coding assistants systematically produce inaccessible code by default (hardcoded fonts, onTapGesture instead of Button, missing labels, no system preference checks) and this skill corrects those patterns./ios-localizationProduction-grade iOS localization skill covering String Catalogs (.xcstrings), CLDR pluralization, SwiftUI/UIKit localization APIs, RTL layout, date/number/currency formatting, and enterprise patterns (modular apps, white-label, accessibility localization). This skill should be used when creating or editing localized iOS strings, working with .xcstrings or .strings files, implementing pluralization, formatting dates/numbers/currencies for display, building RTL-compatible layouts, localizing accessibility labels, setting up localization in Swift Packages, or reviewing code for localization correctness. Use this skill any time someone is working with iOS localization, i18n, l10n, String Catalogs, plural rules, RTL, date formatting, or translated strings — even if they only say 'add a string' or 'format this date' or 'make this work in Arabic.' Also audit any newly generated user-facing iOS code for localization failures before finalizing — AI coding assistants systematically produce broken localization (hardcoded strings, missing plural categories, wrong date formats, left/right instead of leading/trailing) and this skill corrects those patterns. For .xcstrings files that are too large for direct editing, use the bundled Python scripts in scripts/ to validate, add entries, audit completeness, and fix plural categories programmatically./ios-loggingEnterprise skill for iOS production error observability and logging (iOS 15+, Swift 5.5+). The trigger is OBSERVABILITY intent — the user wants errors captured and visible in production, not just handled. Use when: adding os.Logger or replacing print() with structured logging; setting up or integrating a crash SDK (Sentry, Crashlytics, PostHog); auditing error handling for silent failures (catch blocks with no Logger/ErrorReporter call, try? on network/auth/payment operations, Task {} with no do-catch, Combine .replaceError() killing error visibility); adding privacy annotations to logs; integrating MetricKit for OOM/hang detection; or asking why errors are disappearing silently in production. Also use when reviewing any catch block, try?, or Task {} specifically to ensure errors reach a remote crash reporting service — not just for writing error handling in general./ios-securityUse for any iOS security question — whether you're asking about a specific vulnerability, checking if a pattern is secure, or running a full audit. Triggers on: Keychain vs UserDefaults decisions, ATS/NSAllowsArbitraryLoads configuration, certificate pinning implementation, WebView security (UIWebView, WKWebView), hardcoded secrets or API keys, jailbreak/tamper detection, biometric authentication, MASVS controls, OWASP mobile security, App Store rejection risks, and compliance requirements (HIPAA, PCI DSS, GDPR). Also use when someone asks 'is this secure?', 'what should I use instead?', or 'how do I fix this?' about any iOS storage, network, or cryptography pattern./swift-concurrencyUse for any Swift Concurrency question on Apple platforms. Triggers on: actor reentrancy (stale state after await), AsyncStream lifecycle (continuation.finish, onTermination), TaskGroup memory and task throttling (activeProcessorCount), Sendable conformance across actor boundaries (non-Sendable third-party types), SWIFT_STRICT_CONCURRENCY=complete error triage ('Sending X risks causing data races'), Swift 6 / 6.2 migration (nonisolated caller-side isolation, @concurrent), cooperative pool blocking, async/await patterns, and continuation misuse. Also covers @MainActor isolation, structured concurrency, and converting callbacks to async/await. Use whenever the query mentions actor, AsyncStream, TaskGroup, Sendable, nonisolated, withCheckedContinuation, or Swift 6.Other plugins' skills for the same job