Swift Testing #2: 使用 @Suite 分组测试
发布: (2025年12月5日 GMT+8 06:10)
4 min read
原文: Dev.to
Source: Dev.to
介绍
一个 Suite 是一组测试。
在创建包含使用 @Test 标记的测试的结构时,它会自动在测试报告中标记一个 “S”,表示这是一个隐式 Suite。
也可以使用 @Suite 标记显式创建 Suite;在报告中会显示分配的名称。
创建显式 Suite
@Suite("GIVEN some common preconditions")
struct CommonPreconditionsTests {
@Test
func specificAction() throws {
// ...
}
}
嵌套 Suites
可以嵌套 Suites,以更好地描述具有共同功能、场景和前置条件的测试。
一种实用的做法是使用 BDD 的 Gherkin 记法,它定义了多个层级和步骤:
- Feature(特性): 对要测试的功能的高级描述。
- Scenario(场景): Feature 中的具体用例。
- Given(前置): 初始状态或前置条件。
- When(当): 触发场景的动作或事件。
- Then(则): 预期结果或后置条件。
- And(并且): 后续步骤。
使用 Feature 和 Scenario 的示例
@Suite("FEATURE: Calculator")
struct CalculatorTests {
@Suite("SCENARIO: Add two numbers")
struct AddingTwoNumbers {
@Test("GIVEN: I have entered 50 in the calculator AND: I have entered 70 in the calculator WHEN: I press add THEN: the result should be 120 on the screen")
func regularCase() {
let x = 50
let y = 70
let result = x + y
let expected = 120
#expect(result == expected)
}
@Test("GIVEN: I have entered in the calculator AND: I have entered into the calculator WHEN: I press add THEN: the result should be on the Screen")
func generalization() {
let x = 60
let y = 70
let result = x + y
let expected = 130
#expect(result == expected)
}
}
}
生成的测试报告
- FEATURE: Calculator
- SCENARIO: Add two numbers
- GIVEN: I have entered 50 in the calculator AND: I have entered 70 in the calculator WHEN: I press add THEN: the result should be 120 on the screen
- GIVEN: I have entered in the calculator AND: I have entered into the calculator WHEN: I press add THEN: the result should be on the Screen
按共同前置条件分组
如果多个测试共享相同的前置条件(GIVEN),可以将它们放在另一个 Suite 中:
@Suite("FEATURE: Calculator")
struct CalculatorTests {
@Suite("SCENARIO: Subtracting two numbers")
struct SubtractingTwoNumbers {
@Suite("GIVEN common pre‑conditions")
struct CommonPreconditions {
@Test("WHEN: I press subtract once THEN: the result should be ...")
func case1() {
// ...
#expect(result == expected)
}
@Test("WHEN: I press subtract twice THEN: the result should be ...")
func case2() {
// ...
#expect(result == expected)
}
}
}
}
生成的测试报告
- FEATURE: Calculator
- SCENARIO: Subtracting two numbers
- GIVEN: common pre‑conditions
- WHEN: I press subtract once THEN: the result should be ...
- WHEN: I press subtract twice THEN: the result should be ...
注意事项
XCTAssert必须在XCTestCase中使用才能生效;仅将代码迁移到 Swift Testing 并不足够。@Suite允许对测试进行分组和嵌套,从而提升报告的可读性。- 在可能的情况下,使用 Gherkin 记法(Feature/Scenario)来更好地描述测试。