/ios-skills:swift-testingfrom ios-skills
Write and migrate tests using the Swift Testing framework. Covers @Test, @Suite, #expect, #require, parameterized tests, test tags, traits, XCTest migration, mocking, and async test patterns.
Ships in ios-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.
Swift Testing is the modern testing framework for Swift (Xcode 16+, Swift 6+). Prefer it over XCTest for all new unit tests. Use XCTest only for UI tests, performance benchmarks, and snapshot tests.
import Testing
@Test("User can update their display name")
func updateDisplayName() {
var user = User(name: "Alice")
user.name = "Bob"
#expect(user.name == "Bob")
}
@Test("Validates email format") // display name
@Test(.tags(.validation, .email)) // tags
@Test(.disabled("Server migration in progress")) // disabled
@Test(.enabled(if: ProcessInfo.processInfo.environment["CI"] != nil)) // conditional
@Test(.bug("https://github.com/org/repo/issues/42")) // bug reference
@Test(.timeLimit(.minutes(1))) // time limit
@Test("Timeout handling", .tags(.networking), .timeLimit(.seconds(30))) // combined
// #expect records failure but continues execution
#expect(result == 42)
#expect(name.isEmpty == false)
#expect(items.count > 0, "Items should not be empty")
// #expect with error type checking
#expect(throws: ValidationError.self) {
try validate(email: "not-an-email")
}
// #expect with specific error value
#expect {
try validate(email: "")
} throws: { error in
guard let err = error as? ValidationError else { return false }
return err == .empty
}
// #require records failure AND stops test (like XCTUnwrap)
let user = try #require(await fetchUser(id: 1))
#expect(user.name == "Alice")
// #require for optionals -- unwraps or fails
let first = try #require(items.first)
#expect(first.isValid)
Rule: Use #require when subsequent assertions depend on the value. Use #expect for independent checks.
See references/testing-patterns.md for suite organization, confirmation patterns, and known-issue handling.
Mark expected failures so they do not cause test failure:
withKnownIssue("Propane tank is empty") {
#expect(truck.grill.isHeating)
}
// Intermittent / flaky failures
withKnownIssue(isIntermittent: true) {
#expect(service.isReachable)
}
// Conditional known issue
withKnownIssue {
#expect(foodTruck.grill.isHeating)
} when: {
!hasPropane
}
If no known issues are recorded, Swift Testing records a distinct issue notifying you the problem may be resolved.
See references/testing-patterns.md for complete examples of:
Pass any Sendable & Collection to arguments:. Each element runs as an independent test case.
// Enum-based: runs one case per enum value
enum Environment: String, CaseIterable, Sendable {
case development, staging, production
}
@Test("Base URL is valid for all environments", arguments: Environment.allCases)
func baseURLIsValid(env: Environment) throws {
let url = try #require(URL(string: Config.baseURL(for: env)))
#expect(url.scheme == "https")
}
@Test("Fibonacci is positive for small inputs", arguments: 1...20)
func fibonacciPositive(n: Int) {
#expect(fibonacci(n) > 0)
}
Two argument collections produce a cartesian product (every combination):
@Test(arguments: ["light", "dark"], ["iPhone", "iPad"])
func snapshotTest(colorScheme: String, device: String) {
// Runs 4 combinations: light+iPhone, light+iPad, dark+iPhone, dark+iPad
let config = SnapshotConfig(colorScheme: colorScheme, device: device)
#expect(config.isValid)
}
Use zip for 1:1 pairing (avoids cartesian product):
@Test(arguments: zip(
[200, 201, 204],
["OK", "Created", "No Content"]
))
func httpStatusDescription(code: Int, expected: String) {
#expect(HTTPStatus(code).description == expected)
}
Create a CustomTestArgumentProviding conformance or use computed static properties:
struct APIEndpoint: Sendable {
let path: String
let expectedStatus: Int
static let testCases: [APIEndpoint] = [
.init(path: "/users", expectedStatus: 200),
.init(path: "/missing", expectedStatus: 404),
]
}
@Test("API returns expected status", arguments: APIEndpoint.testCases)
func apiStatus(endpoint: APIEndpoint) async throws {
let response = try await client.get(endpoint.path)
#expect(response.statusCode == endpoint.expectedStatus)
}
Declare tags as static members on Tag:
extension Tag {
@Tag static var networking: Self
@Tag static var database: Self
@Tag static var slow: Self
@Tag static var critical: Self
@Tag static var smoke: Self
}
Run tagged tests from Xcode Test Plans or the command line. Tag-based filtering syntax varies by toolchain — verify the exact flags for your Swift version:
# Filter by tag (tooling-specific — verify syntax for your Swift version)
swift test --filter tag:networking
In Xcode, configure Test Plans to include/exclude tags for different CI configurations (smoke tests vs full suite).
@Suite("Shopping Cart Operations")
struct ShoppingCartTests {
let cart: ShoppingCart
// init acts as setUp -- runs before each test in the suite
init() {
cart = ShoppingCart()
cart.add(Product(name: "Widget", price: 9.99))
}
@Test func itemCount() {
#expect(cart.items.count == 1)
}
@Test func totalPrice() {
#expect(cart.total == 9.99)
}
}
Use init for setup and deinit for teardown. For async cleanup, use a TestScoping trait:
@Suite(.tags(.database))
struct DatabaseTests {
let db: TestDatabase
init() async throws {
db = try await TestDatabase.createTemporary()
}
// deinit works for synchronous cleanup (struct suites only use init)
// For async teardown, use TestScoping trait instead
@Test func insertRecord() async throws {
try await db.insert(Record(id: 1, name: "Test"))
let count = try await db.count()
#expect(count == 1)
}
}
Record issues that surface in test output but don't fail the test. Use for performance regressions, deprecated paths, or non-critical checks you want to track.
Issue.record(
"Processing took \(elapsed)s — exceeds 2s target",
severity: .warning
)
@Test functions can be async and throws directly:
@Test func fetchUserProfile() async throws {
let service = UserService(client: MockHTTPClient())
let user = try await service.fetchProfile(id: 42)
#expect(user.name == "Alice")
}
Access actor-isolated state with await:
actor Counter {
private(set) var value = 0
func increment() { value += 1 }
}
@Test func counterIncrements() async {
let counter = Counter()
await counter.increment()
await counter.increment()
let value = await counter.value
#expect(value == 2)
}
Use .timeLimit to prevent tests from hanging indefinitely:
@Test(.timeLimit(.seconds(5)))
func networkCallCompletes() async throws {
let result = try await api.fetchData()
#expect(result.isEmpty == false)
}
If the test exceeds the time limit, it fails immediately with a clear timeout diagnostic.
confirmation replaces XCTestExpectation / fulfill() / waitForExpectations. It verifies that an event occurs the expected number of times:
@Test func notificationPosted() async throws {
// Expects the closure to call confirm() exactly once
try await confirmation("UserDidLogin posted") { confirm in
let center = NotificationCenter.default
let observer = center.addObserver(
forName: .userDidLogin, object: nil, queue: .main
) { _ in
confirm()
}
await loginService.login(user: "test", password: "pass")
center.removeObserver(observer)
}
}
// Expect multiple confirmations
@Test func batchProcessing() async throws {
try await confirmation("Items processed", expectedCount: 3) { confirm in
processor.onItemComplete = { _ in confirm() }
await processor.process(items: [a, b, c])
}
}
Stop a test without marking it passed or failed. The test is recorded as "cancelled" — distinct from failure or a known issue.
@Test func requiresNetwork() throws {
guard NetworkMonitor.shared.isConnected else {
try Test.cancel("No network — skipping integration test")
}
// ... test continues if connected
}
// Enable only on CI
@Test(.enabled(if: ProcessInfo.processInfo.environment["CI"] != nil))
func integrationTest() async throws { ... }
// Disable with a reason
@Test(.disabled("Blocked by #123 -- server migration"))
func brokenEndpoint() async throws { ... }
// Bug reference -- links test to an issue tracker
@Test(.bug("https://github.com/org/repo/issues/42", "Intermittent timeout"))
func flakyNetworkTest() async throws { ... }
@Test(.timeLimit(.minutes(2)))
func longRunningImport() async throws {
try await importer.importLargeDataset()
}
// Apply time limit to entire suite
@Suite(.timeLimit(.seconds(30)))
struct FastTests {
@Test func quick1() { ... }
@Test func quick2() { ... }
}
Create reusable traits for common test configurations:
struct DatabaseTrait: TestTrait, SuiteTrait, TestScoping {
func provideScope(
for test: Test,
testCase: Test.Case?,
performing function: @Sendable () async throws -> Void
) async throws {
let db = try await TestDatabase.setUp()
defer { Task { await db.tearDown() } }
try await function()
}
}
extension Trait where Self == DatabaseTrait {
static var database: Self { .init() }
}
// Usage: any test with .database trait gets a fresh database
@Test(.database)
func insertUser() async throws { ... }
Attach diagnostic data to test results for debugging failures. See references/testing-patterns.md for full examples.
@Test func generateReport() async throws {
let report = try generateReport()
Attachment(report.data, named: "report.json").record()
#expect(report.isValid)
}
Image attachments are available via cross-import overlays — import both Testing and a UI framework:
import Testing
import UIKit
@Test func renderedChart() async throws {
let image = renderer.image { ctx in chartView.drawHierarchy(in: bounds, afterScreenUpdates: true) }
Attachment(image, named: "chart.png").record()
}
Test code that calls exit(), fatalError(), or preconditionFailure(). See references/testing-patterns.md for details.
@Test func invalidInputCausesExit() async {
await #expect(processExitsWith: .failure) {
processInvalidInput() // calls fatalError()
}
}
confirmation with expected counts, not sleep calls.init() in @Suite.sleep in tests. Use confirmation, clock injection, or withKnownIssue.Task cancellation, verify it cancels cleanly.@MainActor.@Test, #expect), not XCTest assertionsfetchUserReturnsNilOnNetworkError not testFetchUser)confirmation(), not Task.sleep.critical, .slow)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub jordancoin/ios-skills-collection --plugin ios-skills4 plugins ship this exact skill · first indexed Jul 18, 2026
206 skills in this plugin
/aso-appstore-screenshotsGenerate high-converting App Store screenshots by analyzing your app's codebase, discovering core benefits, and creating ASO-optimized screenshot images using Nano Banana Pro./cleanseReview code for readability, then simplify it to be easy to follow and understand. Use this skill when the user wants to simplify code, improve readability, clean up for handoff, make code skimmable, reduce complexity, refactor for clarity, strip boilerplate, prepare code for future maintainers, or make a codebase easier to pick up. Trigger liberally — any request touching readability, simplification, cleanup, or "make this easier to understand" should use this skill. Also trigger when the user says things like "review this", "clean this up", "tidy this", "make this simpler", "reduce complexity", "flatten this", "strip the noise", or "I want to understand this code quickly next time I open it".
/critical-reasoningApply critical rationalist epistemology (Popper, Deutsch) to evaluate reasoning, identify errors, and refine understanding. Use when the user explicitly requests help with reasoning - phrases like "help me think this through", "does this make sense", "any flaws in this", "what am I missing", "critique this", "is this reasoning sound", "stress test this idea", "devil's advocate", or any request to evaluate arguments, identify logical problems, or improve thinking. Also use when errors in reasoning are significant enough to materially affect the user's goals, even if not explicitly requested.Other plugins' skills for the same job