К основному содержанию
скилл CX Codex

swift-testing-expert — скилл для Claude Code: тесты на Swift Testing

Помогает писать и разбирать тесты на Swift Testing: макросы #expect и #require, теги, параметризация, миграция с XCTest.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add AvdLee/Swift-Testing-Agent-Skill --skill swift-testing-expert -a claude-code
Открыть на GitHub

Что делает swift-testing-expert

Скилл даёт агенту свод правил по Swift Testing. Он подсказывает, когда оставить XCTest — UI-автоматизация на XCUIApplication, метрики производительности на XCTMetric, код тестов только на Objective-C. Всё остальное переводится на Swift Testing.

Внутри — контракт поведения агента и карта ссылок: references/expectations.md про макросы, references/parameterized-testing.md про параметризацию, references/parallelization-and-isolation.md про параллельный запуск и .serialized, references/migration-from-xctest.md про переход с XCTest. Есть шаблон быстрой триажи: сначала выяснить версию Xcode и Swift, чем тесты написаны сейчас, падают ли они стабильно или мигают.

Импорт Testing разрешён только в тестовых таргетах, в приложение или библиотеку его тянуть нельзя. Миграцию скилл советует вести по шагам: сперва утверждения, потом организация сьютов, затем параметризация и трейты. Если тесты делят базу или глобальное состояние, сначала предлагается развести зависимости, а .serialized — только как временная мера.

Какие задачи решает

  • перевести сьют с XCTest на Swift Testing без переписывания всего сразу
  • разобраться, когда нужен #require, а когда хватит #expect
  • заменить десяток однотипных тестов одним параметризованным
  • найти причину мигающих тестов на общей базе
  • отфильтровать тесты по тегам вместо списков имён в test plan

Примеры запросов агенту

  • Перепиши этот XCTest-сьют на Swift Testing, начни с утверждений
  • Сделай из этих однотипных тестов один параметризованный @Test(arguments:)
  • Тест мигает на общей базе — предложи, как изолировать зависимости

Как установить swift-testing-expert

1Через Skills CLI (Vercel)

npx skills add AvdLee/Swift-Testing-Agent-Skill --skill swift-testing-expert -a claude-code

2Вручную: положить файлы

~/.claude/skills/swift-testing-expert/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/swift-testing-expert/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о swift-testing-expert

Как установить swift-testing-expert в Claude Code?

Выполните npx skills add AvdLee/Swift-Testing-Agent-Skill --skill swift-testing-expert -a claude-code. Скилл окажется в ~/.claude/skills/swift-testing-expert/SKILL.md.

Что делает swift-testing-expert?

Даёт агенту правила по Swift Testing: структура тестов, макросы #expect и #require, трейты и теги, параметризация, параллельный запуск, ожидание асинхронного кода и переход с XCTest.

Можно ли использовать скилл в проектах, где ещё живёт XCTest?

Да, миграция задумана постепенной. XCTest остаётся для UI-автоматизации, метрик производительности и тестов только на Objective-C, остальное переносится на Swift Testing.

Исходный текст

SKILL.md · MIT
---
name: swift-testing-expert
description: 'Expert guidance for Swift Testing: test structure, #expect/#require macros, traits and tags, parameterized tests, test plans, parallel execution, async waiting patterns, and XCTest migration. Use when writing new Swift tests, modernizing XCTest suites, debugging flaky tests, or improving test quality and maintainability in Apple-platform or Swift server projects.'
---

# Swift Testing

## Overview

Use this skill to write, review, migrate, and debug Swift tests with modern Swift Testing APIs. Prioritize readable tests, robust parallel execution, clear diagnostics, and incremental migration from XCTest where needed.

## Agent behavior contract (follow these rules)

1. Prefer Swift Testing for Swift unit and integration tests, but keep XCTest for UI automation (`XCUIApplication`), performance metrics (`XCTMetric`), and Objective-C-only test code.
2. Treat `#expect` as the default assertion and use `#require` when subsequent lines depend on a prerequisite value.
3. Default to parallel-safe guidance. If tests are not isolated, first propose fixing shared state before applying `.serialized`.
4. Prefer traits for behavior and metadata (`.enabled`, `.disabled`, `.timeLimit`, `.bug`, tags) over naming conventions or ad-hoc comments.
5. Recommend parameterized tests when multiple tests share logic and differ only in input values.
6. Use `@available` on test functions for OS-gated behavior instead of runtime `#available` checks inside test bodies; never annotate suite types with `@available`.
7. Keep migration advice incremental: convert assertions first, then organize suites, then introduce parameterization/traits.
8. Only import `Testing` in test targets, never in app/library/binary targets.

## First 60 seconds (triage template)

- Clarify the goal: new tests, migration, flaky failures, performance, CI filtering, or async waiting.
- Collect minimal facts:
  - Xcode/Swift version and platform targets
  - Whether tests currently use XCTest, Swift Testing, or both
  - Whether failures are deterministic or flaky
  - Whether tests access shared resources (database, files, network, global state)
- Branch quickly:
  - repetitive tests -> parameterized tests
  - noisy or flaky failures -> known issue handling and test isolation
  - migration questions -> XCTest mapping and coexistence strategy
  - async callback complexity -> continuation/await patterns

## Routing map (read the right reference fast)

- Test building blocks and suite organization -> `references/fundamentals.md`
- `#expect`, `#require`, and throw expectations -> `references/expectations.md`
- Traits, tags, and Xcode test-plan filtering -> `references/traits-and-tags.md`
- Parameterized test design and combinatorics -> `references/parameterized-testing.md`
- Default parallel execution, `.serialized`, isolation strategy -> `references/parallelization-and-isolation.md`
- Test speed, determinism, and flakiness prevention -> `references/performance-and-best-practices.md`
- Async waiting and callback bridging -> `references/async-testing-and-waiting.md`
- XCTest coexistence and migration workflow -> `references/migration-from-xctest.md`
- Test navigator/report workflows and diagnostics -> `references/xcode-workflows.md`
- Index and quick navigation -> `references/_index.md`

## Common pitfalls -> next best move

- Repetitive `testFooCaseA/testFooCaseB/...` methods -> replace with one parameterized `@Test(arguments:)`.
- Failing optional preconditions hidden in later assertions -> `try #require(...)` then assert on unwrapped value.
- Flaky integration tests on shared database -> isolate dependencies or in-memory repositories; use `.serialized` only as a transition step.
- Disabled tests that silently rot -> prefer `withKnownIssue` for temporary known failures to preserve signal.
- Unclear failure values for complex types -> conform type to `CustomTestStringConvertible` for focused test diagnostics.
- Test-plan include/exclude by names -> use tags and tag-based filters instead.

## Verification checklist

- Confirm each test has a single clear behavior and expressive display name when needed.
- Confirm prerequisites use `#require` where failure should stop the test.
- Confirm repeated logic is parameterized instead of duplicated.
- Confirm tests are parallel-safe or intentionally serialized with rationale.
- Confirm async code is awaited and callback APIs are bridged safely.
- Confirm migration keeps unsupported XCTest-only scenarios on XCTest.

## References

- `references/_index.md`
- `references/fundamentals.md`
- `references/expectations.md`
- `references/traits-and-tags.md`
- `references/parameterized-testing.md`
- `references/parallelization-and-isolation.md`
- `references/performance-and-best-practices.md`
- `references/async-testing-and-waiting.md`
- `references/migration-from-xctest.md`
- `references/xcode-workflows.md`

© AvdLee · MIT · AvdLee/Swift-Testing-Agent-Skill

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

Всё по теме «Тесты и QA» →
improve-codebase-architecture Matt Pocock Скилл ищет архитектурные узкие места в кодовой базе и показывает варианты углубления модулей в HTML-отчёте. Подойдёт для ревью перед рефакторингом. 1 163 035установок design-taste-frontend Leonxlnx Скилл задаёт арт-дирекцию для публичных страниц и рабочих экранов, а затем проверяет результат в браузере по скриншотам. Нужен, когда интерфейс выглядит шаблонным или недоработанным. CX Codex +1 678 700установок tdd Matt Pocock Скилл управляет циклом красный-зелёный в TDD: проверяет, что тесты пишутся до кода, держит их на уровне публичных интерфейсов и не завязывает на внутреннюю структуру. 1 141 062установок skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. 414 180установок agent-browser vercel-labs Скилл управляет браузером через CLI: открывает страницы, заполняет формы, нажимает кнопки и проверяет веб-приложения. Подходит для задач, где агенту нужно действовать в интерфейсе. CX Codex +1 1 200 000установок prototype Matt Pocock Создаёт временный прототип, чтобы проверить логику, модель состояния или вид интерфейса до работы над основным кодом. 986 201установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой