Swift Testing #1: 将 XCTest 测试套件迁移到 Swift Testing

发布: (2025年12月5日 GMT+8 05:54)
3 min read
原文: Dev.to

Source: Dev.to

转换到 Swift Testing

import XCTest
@testable import ProductionProject

class SomeXCTest_deprecated: XCTestCase {
    func testX() throws {
        // GIVEN
        // ...

        // WHEN
        // ...

        // THEN ...
        XCTAssert(A == B, "Expected \(A) but received \(B)")
    }
}
import Testing
@testable import ProductionProject

struct SomeTest {
    @Test
    func x() throws {
        // GIVEN
        // ...

        // WHEN
        // ...

        // THEN ...
        #expect(A == B, "Expected \(A) but received \(B)")
    }
}

Swift Testing 从 Xcode 16 起可用,并且根据官方文档,需要 Swift 6。不过,也可以在 Swift 5 项目中使用它。

为测试命名

在 Swift Testing 中,测试名称可以来源于方法名或 @Test 标记中的描述。也可以使用 反引号(backticks)为方法命名并包含空格。两种方式不能在同一个测试中混用。

import Testing
@testable import ProductionProject

struct SomeTest {
    @Test("GIVEN some conditions, WHEN executing something, THEN it should return X")
    func x() throws {
        // ...
    }

    func `GIVEN some conditions, WHEN executing something, THEN it should...`() throws {
        // ...
    }

    @Test
    func GIVENsomeconditionsWHENexecutingsomethingTHENitShouldReturnX() throws {
        // ...
    }
}

其他特性

  • 可以在同一个文件和项目中混合使用 XCTest 和 Swift Testing 的测试。
  • 不必强制把所有 XCTest 测试迁移到 Swift Testing。
  • 该框架更倾向于使用 值类型;如果不需要 tearDown(在类中通过 deinit 实现),推荐使用 struct

移除手动的 Swift Testing 依赖

Swift and Tips 视频中包含了 SPM 包 swift-testing(0.10 版)。在该版本中,失败的测试(#expect(1 == 2))会在控制台显示为失败,但在报告中却显示为成功。

要使用 Xcode 26 内置的版本,需要删除 SPM 依赖:

  1. 删除依赖OnlineStoreMV > Project > Package Dependency → 删除 swift-testing
  2. 编译:尝试编译时出现错误 “unable to find module dependency _TestingInternals”
  3. 解决方案:清理项目(⌘⇧K)后重新编译。

XCTAssert@Test 的互操作性

XCTAssert 只能在继承自 XCTestCase 的类中使用,因为它由 XCTestRunXCTestSuite 中执行。因此,在标记为 @Test 的方法里使用 XCTAssert 不会导致测试失败。

import XCTest
import Testing

struct MyTests {
    @Test
    func something() {
        XCTAssert(2 == 3)   // 不起作用:测试仍然通过。
        #expect(2 == 3)     // 正确:测试会失败。
    }
}

不过,仅包含 XCTAssert@Test 方法仍会被 Swift Testing 的运行器识别,只是失败不会被正确记录。

参考文献

  • 视频 Mastering Swift Testing: Installation & Refactoring from XCTest to @test MacroYouTube
  • 播放列表 Swift Testing(Swift and Tips),YouTube
  • 官方 Swift Testing 文档,Apple Developer
  • WWDC 2024 Meet Swift TestingApple Videos
  • WWDC 2024 Go further with Swift TestingApple Videos
  • Swift Testing GitHub 仓库,github.com/swiftlang/swift-testing
  • 文章 Is MVVM Necessary for Developing Apps with SwiftUI?Swift and Tips
  • 项目 OnlineStore made with SwiftUI (Vanilla) and ObservationGitHub
Back to Blog

相关文章

阅读更多 »