swift-unit-testing
БесплатноБез исполняемых скриптовНе проверенWrite, modify, and review deterministic Swift unit tests using the Swift Testing framework. Use when working with @Test,
от nonameplum★ 17 звёзд на GitHubОб этом скилле
Swift Unit Testing: Agent Playbook
Audience: LLM coding agents generating or modifying Swift unit tests Framework: Swift Testing (
import Testing)
Quick Reference (Read First)
| Requirement | Rule |
|---|---|
| Framework | Swift Testing (@Test, #expect, #require) — never XCTest for new tests |
| Test structure | AAA pattern with // Arrange, // Act, // Assert comments |
| Naming | operation_condition_expectedResult — no "test" prefix, no "should" |
| SUT variable | Always sut — never store, context, container for the main subject |
| Helpers | make... prefix — placed at bottom of file |
| Dependencies | Fakes/stubs via closures — avoid assertion-heavy mocks |
| Isolation | Deterministic, in-memory, no network, no disk, no real time |
Non-Negotiables (NEVER Violate)
- NEVER use XCTest for new tests — use Swift Testing exclusively
- NEVER write flaky tests — no network, no real filesystem, no
Date(), noUUID() - NEVER combine multiple behaviors in one test — split into separate
@Testfunctions - NEVER skip AAA comments — every test must have
// Arrange,// Act,// Assert - NEVER use magic strings/numbers — use named constants or fixture values
- NEVER guess CLI commands — insert
> TODO:marker if unknown - NEVER modify unrelated code — touch only what the task requires
- NEVER invent abstractions — follow existing patterns in nearest neighbor tests
Workflow (Execute Every Time)
Step 1: Clarify Intent
Before writing any code, answer:
- What single behavior is being verified?
- What is the exact given / when / then?
- What is out of scope?
If unclear, stop and ask.
Step 2: Locate Insertion Point
Tests/
├── {ModuleName}Tests/ ← SwiftPM default (mirror source hierarchy)
│ ├── Test{Subject}.swift
│ └── TestSupport/
│ └── fakes, helpers
└── {AppName}Tests/ ← Xcode test target
└── Test{Subject}.swift
- Find the closest existing test file under
Tests/or the test target folder - If no test file exists, create one following naming convention
- Mirror the source hierarchy if the repo already does so
- Check nearest neighbor tests for patterns before inventing structure
Step 3: Select Testing Approach
| Subject Type | Approach |
|---|---|
| Pure function/utility | Direct call + #expect |
| SwiftData schema (if used) | In-memory container + @Suite(.serialized) |
| SwiftData migration (if used) | File-based container (only when testing cross-instance migration) |
Step 4: Write the Test
Follow this exact structure:
import Testing
@testable import {ModuleName}
struct Test{Subject} {
@Test
func operation_condition_expectedResult() throws {
// Arrange
let sut = makeSut()
// Act
let result = sut.performOperation()
// Assert
#expect(result == expectedValue)
}
// MARK: - Helpers
private func makeSut() -> Subject {
Subject()
}
}
Step 5: Verify
- Run only the relevant test(s) — not the full suite
- Confirm deterministic: run twice, same result
- Check for linter errors
Framework: Swift Testing
Import Statement
import Testing
@testable import {AppTarget}
### Test Container
Prefer `struct`. Use `class` only when `deinit` cleanup is required.
```swift
struct TestUserService {
@Test
func fetchUser_validId_returnsUser() async throws {
// ...
}
}
Assertions
| Use Case | Macro |
|---|---|
| Boolean/equality | #expect(value == expected) |
| Unwrap optional | let x = try #require(optionalValue) |
| Verify throws | #expect(throws: SomeError.self) { try operation() } |
| Verify no throw | #expect(throws: Never.self) { try operation() } |
NEVER use XCTest assertions (XCTAssert*) in Swift Testing files.
Display Names
Use @Test("...") only when the function name cannot be expressive:
// ✅ Display name adds value
@Test("V0→V1 migration preserves user recordings")
func migrateFromV0_preservesRecordings() throws { }
// ❌ Display name duplicates function name — remove it
@Test("Save user persists to store")
func saveUser_persistsToStore() throws { }
Naming Conventions
File Names
| Pattern | Example |
|---|---|
Test{Subject}.swift |
TestMigrationPlan.swift |
Test{Subject}+{Aspect}.swift |
TestModelContainer+Migration.swift |
Test Function Names
Pattern: operation_condition_expectedResult
// ✅ Good
func createContainer_withUnversionedStore_migratesSuccessfully()
func fetchUser_nonExistentId_returnsNil()
func onAppear_setsInitialFocus()
// ❌ Bad — verbose, uses "should", uses "test" prefix
func testThatWhenUserIsSavedThenItShouldBeFetched()
Variable Names
// ✅ Always use `sut` for system under test
let sut = makeSut()
var sut = TestStore(...)
// ❌ Never use inconsistent name
Установить swift-unit-testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл swift-unit-testing?
Write, modify, and review deterministic Swift unit tests using the Swift Testing framework. Use when working with @Test,
Как установить скилл swift-unit-testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swift-unit-testing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic