claude-code/claude-zh/rules/swift/testing.md

46 lines
1.1 KiB
Markdown
Raw Normal View History

2026-02-27 13:45:37 +00:00
---
paths:
- "**/*.swift"
- "**/Package.swift"
---
# Swift 測試 (Testing)
> 本檔案擴展了 [common/testing.md](../common/testing.md),包含 Swift 特定內容。
## 框架 (Framework)
新測試請使用 **Swift Testing** (`import Testing`)。使用 `@Test``#expect`
```swift
@Test("使用者建立時會驗證電子郵件")
func userCreationValidatesEmail() throws {
#expect(throws: ValidationError.invalidEmail) {
try User(email: "not-an-email")
}
}
```
## 測試隔離 (Test Isolation)
每個測試都會獲得一個新的實例 — 在 `init` 中設定,在 `deinit` 中清理。測試之間不存在共享的可變狀態。
## 參數化測試 (Parameterized Tests)
```swift
@Test("驗證格式", arguments: ["json", "xml", "csv"])
func validatesFormat(format: String) throws {
let parser = try Parser(format: format)
#expect(parser.isValid)
}
```
## 覆蓋率 (Coverage)
```bash
swift test --enable-code-coverage
```
## 參考資源
參見技能 (Skill)`swift-protocol-di-testing`,獲取基於協定的依賴注入以及搭配 Swift Testing 的 Mock 模式。