Swift Testing
添加 SPM 包并依赖 TraceraTesting:
.package(url: "https://github.com/tracera-dev/tracera-swift.git", from: "0.1.0"),
// …
.product(name: "TraceraTesting", package: "tracera-swift"),
需要 Swift ≥ 6(macOS 15 / Xcode 16;见 自动化测试适配器)。
环境变量与运行模式:自动化测试适配器。
绑定 testCaseId 与 autotestName
优先使用声明式绑定:
@Test("checkout", .traceraId(42))
func checkout() {
// …
}
@Test("login as {user}", .traceraId(42), arguments: ["alice", "bob"])
func login(user: String) {
// …
}
当 id 不是编译期常量时,用 .tracera 打开 pin,再命令式绑定:
@Test("checkout", .tracera)
func checkout() {
Tracera.testCase(42)
// Tracera.testCase(42, "e2e/checkout")
}
跳过
使用 skip("reason"),以便原因作为 comment 写入结果:
@Test("checkout", .traceraId(42))
func checkout() throws {
try skip("needs a seeded account")
}
步骤
使用 Tracera.step("…") { … }(同步或 async)。setup / teardown 内的步骤进入结果的 准备 / 清理;其余步骤进入 测试。
@Test("checkout", .traceraId(10))
func checkout() throws {
try setup("open shop") {}
try Tracera.step("add item") {
Tracera.step("nested leaf") {}
}
try teardown("close shop") {}
}
注释、错误与附件
限制与允许的 MIME 类型:自动化测试适配器。
Tracera.comment、Tracera.error 和附件会添加到当前打开的步骤;若没有打开的步骤,则添加到结果。Tracera.attachmentFile 接收文件路径;Tracera.attachmentBytes 接收名称和字节(MIME 类型可选)。附件在结果上报时上传。
Tracera.comment("result-level note")
Tracera.error("result-level error")
Tracera.attachmentFile("Fixtures/screenshot.png")
Tracera.step("open login") {
Tracera.comment("step note")
Tracera.attachmentBytes("body.json", data: Data(#"{"ok":true}"#.utf8), mimeType: "application/json")
}
若在 Task 中调用 Tracera API(步骤、注释、错误、附件),请先在测试中调用 getContext(),再用 runWithContext 运行 worker — 否则这些调用不会写入报告:
let ctx = getContext()
Task {
await runWithContext(ctx) {
Tracera.step("worker") { /* ... */ }
}
}
参数化测试
每一行 arguments 都是独立用例。在 @Test("…") 标题或 .traceraId(…, name:) 中放入 {user}、{0} 等占位符,使每一行有自己的 autotestName:
@Test("login as {user}", .traceraId(7), arguments: ["alice", "bob"])
func login(user: String) {
Tracera.step("sign in") { /* ... */ }
}