Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

swift-unit-testing

БесплатноБез исполняемых скриптовНе проверен

Write, modify, and review deterministic Swift unit tests using the Swift Testing framework. Use when working with @Test,

nonameplumот 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)

  1. NEVER use XCTest for new tests — use Swift Testing exclusively
  2. NEVER write flaky tests — no network, no real filesystem, no Date(), no UUID()
  3. NEVER combine multiple behaviors in one test — split into separate @Test functions
  4. NEVER skip AAA comments — every test must have // Arrange, // Act, // Assert
  5. NEVER use magic strings/numbers — use named constants or fixture values
  6. NEVER guess CLI commands — insert > TODO: marker if unknown
  7. NEVER modify unrelated code — touch only what the task requires
  8. 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
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить swift-unit-testing с