axiom-testing-async by charleswiltgen/axiom
npx skills add https://github.com/charleswiltgen/axiom --skill axiom-testing-async使用 Swift Testing 框架测试 async/await 代码的现代模式。
✅ 适用于以下情况:
❌ 不适用于以下情况:
| XCTest | Swift Testing |
|---|---|
XCTestExpectation | confirmation { } |
wait(for:timeout:) | await confirmation |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
@MainActor 隐式 | @MainActor 显式 |
| 默认串行 | 默认并行 |
XCTAssertEqual() | #expect() |
continueAfterFailure | 每个期望使用 #require |
@Test func fetchUser() async throws {
let user = try await api.fetchUser(id: 1)
#expect(user.name == "Alice")
}
适用于没有异步重载的 API:
@Test func legacyAPI() async throws {
let result = try await withCheckedThrowingContinuation { continuation in
legacyFetch { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
#expect(result.isValid)
}
当回调应恰好触发一次时:
@Test func notificationFires() async {
await confirmation { confirm in
NotificationCenter.default.addObserver(
forName: .didUpdate,
object: nil,
queue: .main
) { _ in
confirm() // 必须恰好调用一次
}
triggerUpdate()
}
}
@Test func delegateCalledMultipleTimes() async {
await confirmation(expectedCount: 3) { confirm in
delegate.onProgress = { progress in
confirm() // 调用 3 次
}
startDownload() // 触发 3 次进度更新
}
}
@Test func noErrorCallback() async {
await confirmation(expectedCount: 0) { confirm in
delegate.onError = { _ in
confirm() // 应永不调用
}
performSuccessfulOperation()
}
}
@Test @MainActor func viewModelUpdates() async {
let vm = ViewModel()
await vm.load()
#expect(vm.items.count > 0)
#expect(vm.isLoading == false)
}
@Test(.timeLimit(.seconds(5)))
func slowOperation() async throws {
try await longRunningTask()
}
@Test func invalidInputThrows() async throws {
await #expect(throws: ValidationError.self) {
try await validate(input: "")
}
}
// 特定错误
@Test func specificError() async throws {
await #expect(throws: NetworkError.notFound) {
try await api.fetch(id: -1)
}
}
@Test func firstVideo() async throws {
let videos = try await videoLibrary.videos()
let first = try #require(videos.first) // 如果为 nil 则失败
#expect(first.duration > 0)
}
@Test("Video loading", arguments: [
"Beach.mov",
"Mountain.mov",
"City.mov"
])
func loadVideo(fileName: String) async throws {
let video = try await Video.load(fileName)
#expect(video.isPlayable)
}
参数会自动并行运行。
Swift Testing 默认并行运行测试(与 XCTest 不同)。
// ❌ 共享可变状态 — 竞态条件
var sharedCounter = 0
@Test func test1() async {
sharedCounter += 1 // 数据竞争!
}
@Test func test2() async {
sharedCounter += 1 // 数据竞争!
}
// ✅ 每个测试获得新实例
struct CounterTests {
var counter = Counter() // 每个测试都是新的
@Test func increment() {
counter.increment()
#expect(counter.value == 1)
}
}
当测试必须按顺序运行时:
@Suite("Database tests", .serialized)
struct DatabaseTests {
@Test func createRecord() async { /* ... */ }
@Test func readRecord() async { /* ... */ } // 在 create 之后
@Test func deleteRecord() async { /* ... */ } // 在 read 之后
}
注意:其他不相关的测试仍会并行运行。
// ❌ 不稳定 — 任意等待时间
@Test func eventFires() async {
setupEventHandler()
try await Task.sleep(for: .seconds(1)) // 希望它发生了?
#expect(eventReceived)
}
// ✅ 确定性 — 等待实际事件
@Test func eventFires() async {
await confirmation { confirm in
onEvent = { confirm() }
triggerEvent()
}
}
// ❌ 数据竞争 — ViewModel 可能是 MainActor
@Test func viewModel() async {
let vm = ViewModel()
await vm.load() // 可能导致数据竞争警告
}
// ✅ 显式隔离
@Test @MainActor func viewModel() async {
let vm = ViewModel()
await vm.load()
}
// ❌ 测试立即通过 — 不等待回调
@Test func callback() async {
api.fetch { result in
#expect(result.isSuccess) // 在测试结束前从未执行
}
}
// ✅ 等待回调
@Test func callback() async {
await confirmation { confirm in
api.fetch { result in
#expect(result.isSuccess)
confirm()
}
}
}
// ❌ 测试相互干扰
@Test func writeFile() async {
try! "data".write(to: sharedFileURL, atomically: true, encoding: .utf8)
}
@Test func readFile() async {
let data = try! String(contentsOf: sharedFileURL) // 可能失败!
}
// ✅ 使用唯一文件或 .serialized
@Test func writeAndRead() async {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
try! "data".write(to: url, atomically: true, encoding: .utf8)
let data = try! String(contentsOf: url)
#expect(data == "data")
}
// XCTest
func testFetch() {
let expectation = expectation(description: "fetch")
api.fetch { result in
XCTAssertNotNil(result)
expectation.fulfill()
}
wait(for: [expectation], timeout: 5)
}
// Swift Testing
@Test func fetch() async {
await confirmation { confirm in
api.fetch { result in
#expect(result != nil)
confirm()
}
}
}
// XCTest
class MyTests: XCTestCase {
var service: Service!
override func setUp() async throws {
service = try await Service.create()
}
}
// Swift Testing
struct MyTests {
let service: Service
init() async throws {
service = try await Service.create()
}
@Test func example() async {
// 使用 self.service
}
}
WWDC : 2024-10179, 2024-10195
文档 : /testing, /testing/confirmation
技能 : axiom-swift-testing, axiom-ios-testing
每周安装量
97
代码仓库
GitHub 星标数
601
首次出现
2026 年 1 月 21 日
安全审计
安装于
opencode79
codex73
claude-code73
gemini-cli72
cursor70
github-copilot69
Modern patterns for testing async/await code with Swift Testing framework.
✅ Use when:
❌ Don't use when:
| XCTest | Swift Testing |
|---|---|
XCTestExpectation | confirmation { } |
wait(for:timeout:) | await confirmation |
@MainActor implicit | @MainActor explicit |
| Serial by default | Parallel by default |
XCTAssertEqual() | #expect() |
continueAfterFailure | #require per-expectation |
@Test func fetchUser() async throws {
let user = try await api.fetchUser(id: 1)
#expect(user.name == "Alice")
}
For APIs without async overloads:
@Test func legacyAPI() async throws {
let result = try await withCheckedThrowingContinuation { continuation in
legacyFetch { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
#expect(result.isValid)
}
When a callback should fire exactly once:
@Test func notificationFires() async {
await confirmation { confirm in
NotificationCenter.default.addObserver(
forName: .didUpdate,
object: nil,
queue: .main
) { _ in
confirm() // Must be called exactly once
}
triggerUpdate()
}
}
@Test func delegateCalledMultipleTimes() async {
await confirmation(expectedCount: 3) { confirm in
delegate.onProgress = { progress in
confirm() // Called 3 times
}
startDownload() // Triggers 3 progress updates
}
}
@Test func noErrorCallback() async {
await confirmation(expectedCount: 0) { confirm in
delegate.onError = { _ in
confirm() // Should never be called
}
performSuccessfulOperation()
}
}
@Test @MainActor func viewModelUpdates() async {
let vm = ViewModel()
await vm.load()
#expect(vm.items.count > 0)
#expect(vm.isLoading == false)
}
@Test(.timeLimit(.seconds(5)))
func slowOperation() async throws {
try await longRunningTask()
}
@Test func invalidInputThrows() async throws {
await #expect(throws: ValidationError.self) {
try await validate(input: "")
}
}
// Specific error
@Test func specificError() async throws {
await #expect(throws: NetworkError.notFound) {
try await api.fetch(id: -1)
}
}
@Test func firstVideo() async throws {
let videos = try await videoLibrary.videos()
let first = try #require(videos.first) // Fails if nil
#expect(first.duration > 0)
}
@Test("Video loading", arguments: [
"Beach.mov",
"Mountain.mov",
"City.mov"
])
func loadVideo(fileName: String) async throws {
let video = try await Video.load(fileName)
#expect(video.isPlayable)
}
Arguments run in parallel automatically.
Swift Testing runs tests in parallel by default (unlike XCTest).
// ❌ Shared mutable state — race condition
var sharedCounter = 0
@Test func test1() async {
sharedCounter += 1 // Data race!
}
@Test func test2() async {
sharedCounter += 1 // Data race!
}
// ✅ Each test gets fresh instance
struct CounterTests {
var counter = Counter() // Fresh per test
@Test func increment() {
counter.increment()
#expect(counter.value == 1)
}
}
When tests must run sequentially:
@Suite("Database tests", .serialized)
struct DatabaseTests {
@Test func createRecord() async { /* ... */ }
@Test func readRecord() async { /* ... */ } // After create
@Test func deleteRecord() async { /* ... */ } // After read
}
Note : Other unrelated tests still run in parallel.
// ❌ Flaky — arbitrary wait time
@Test func eventFires() async {
setupEventHandler()
try await Task.sleep(for: .seconds(1)) // Hope it happened?
#expect(eventReceived)
}
// ✅ Deterministic — waits for actual event
@Test func eventFires() async {
await confirmation { confirm in
onEvent = { confirm() }
triggerEvent()
}
}
// ❌ Data race — ViewModel may be MainActor
@Test func viewModel() async {
let vm = ViewModel()
await vm.load() // May cause data race warnings
}
// ✅ Explicit isolation
@Test @MainActor func viewModel() async {
let vm = ViewModel()
await vm.load()
}
// ❌ Test passes immediately — doesn't wait for callback
@Test func callback() async {
api.fetch { result in
#expect(result.isSuccess) // Never executed before test ends
}
}
// ✅ Waits for callback
@Test func callback() async {
await confirmation { confirm in
api.fetch { result in
#expect(result.isSuccess)
confirm()
}
}
}
// ❌ Tests interfere with each other
@Test func writeFile() async {
try! "data".write(to: sharedFileURL, atomically: true, encoding: .utf8)
}
@Test func readFile() async {
let data = try! String(contentsOf: sharedFileURL) // May fail!
}
// ✅ Use unique files or .serialized
@Test func writeAndRead() async {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
try! "data".write(to: url, atomically: true, encoding: .utf8)
let data = try! String(contentsOf: url)
#expect(data == "data")
}
// XCTest
func testFetch() {
let expectation = expectation(description: "fetch")
api.fetch { result in
XCTAssertNotNil(result)
expectation.fulfill()
}
wait(for: [expectation], timeout: 5)
}
// Swift Testing
@Test func fetch() async {
await confirmation { confirm in
api.fetch { result in
#expect(result != nil)
confirm()
}
}
}
// XCTest
class MyTests: XCTestCase {
var service: Service!
override func setUp() async throws {
service = try await Service.create()
}
}
// Swift Testing
struct MyTests {
let service: Service
init() async throws {
service = try await Service.create()
}
@Test func example() async {
// Use self.service
}
}
WWDC : 2024-10179, 2024-10195
Docs : /testing, /testing/confirmation
Skills : axiom-swift-testing, axiom-ios-testing
Weekly Installs
97
Repository
GitHub Stars
601
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode79
codex73
claude-code73
gemini-cli72
cursor70
github-copilot69
测试策略完整指南:单元/集成/E2E测试金字塔与自动化实践
11,200 周安装
Laravel开发专家技能:PHP最佳实践、Eloquent ORM、API构建与Web开发解决方案
138 周安装
WCAG 无障碍审计工具 - 网页可访问性合规检测与评估指南 (WCAG 2.1/2.2)
212 周安装
Mantine Form 表单库:React 表单验证与状态管理解决方案 | 开源 UI 组件
246 周安装
英式商务英语写作指南 | 专业商务沟通、英式拼写与邮件礼仪
234 周安装
高级质量保证工程师技能:自动化测试、缺陷管理与CI/CD集成
122 周安装
AI内容检测工具 - 使用HumanizerAI API精准识别AI生成文本,提供详细分析报告
150 周安装