跳转至

Swift 测试

此文件使用 Swift 特定内容扩展 common/testing.md。

框架

对于新测试,使用 Swift Testing(import Testing)。使用 @Test 和 #expect:

@Test("User creation validates email")
func userCreationValidatesEmail() throws {
    #expect(throws: ValidationError.invalidEmail) {
        try User(email: "not-an-email")
    }
}

测试隔离

每个测试获取新的实例 — 在 init 中设置,在 deinit 中清理。不要在测试之间共享可变状态。

参数化测试

@Test("Validates formats", arguments: ["json", "xml", "csv"])
func validatesFormat(format: String) throws {
    let parser = try Parser(format: format)
    #expect(parser.isValid)
}

覆盖率

swift test --enable-code-coverage

参考

关于基于协议的依赖注入和 Swift Testing 的模拟模式,请参见技能:swift-protocol-di-testing。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC