数据驱动测试

一个 Swift 包,为你的项目提供数据驱动的测试功能。

Tests Lint CocoaPods Compatible

用法

要使用数据驱动测试运行测试,你只需要在你的测试用例中运行 dataTests 方法。

@testable import DataDrivenTesting
import XCTest

final class DataDrivenTests: XCTestCase {
    func testDescriptionFromInteger() {
        dataTests([
            TestData((input: 1, expected: "1")),
            TestData((input: 2, expected: "2")),
        ]) { testData, _ in
            let result = testData.data.input.description

            XCTAssertEqual(result, testData.data.expected, file: testData.file, line: testData.line)
        }
    }
}

这将使用传递的闭包为数组中的每个数据运行测试。为了获得更易读的测试结果,你可以在 Xcode 的 Report Navigator 中查看。 它会显示所有测试用例以及用于运行它们的数据。

Report Navigator with default activity name

将文件和行参数传递给 XCTAssertEqual 是可选的,但它将帮助你在代码中找到失败的测试用例。

Failing test

你也可以通过将名称作为第二个参数传递给 TestData 结构体来更改默认的活动名称。

    func testSumOfInt() {
        dataTests([
            .init(([], 0), name: "Empty array"),
            .init(([1], 1), name: "One value in array"),
            .init(([2,3], 5), name: "Two values in array"),

        ]) { testData, activity in
            let result = testData.data.0.reduce(0, +)

            XCTAssertEqual(result, testData.data.1, file: testData.file, line: testData.line)
        }
    }

这将导致 Report Navigator 如下所示

Report Navigator with custom activity name

如果需要向测试用例添加任何附件,可以使用闭包中的 XCTActivity 参数。

    private struct CEO: Encodable {
        let firstName: String
        let lastName: String
    }

    func testUsingActivity() {
        dataTests([
            TestData(CEO(firstName: "Steve", lastName: "Jobs")),
            TestData(CEO(firstName: "Tim", lastName: "Cook")),
        ]) { testData, activity in
            let json = try! JSONEncoder().encode(testData.data)

            let attachment = XCTAttachment(data: json)
            attachment.lifetime = .keepAlways
            activity.add(attachment)
        }
    }

要求

安装

Xcode

⚠️警告:默认情况下,Xcode 会尝试将 DataDrivenTesting 包添加到项目的主应用程序/框架目标。请确保将 DataDrivenTesting 添加到测试目标,如下面的最后一步中所述。

  1. File 菜单中,导航到 Swift Packages 并选择 Add Package Dependency…
  2. 输入包存储库 URL:https://github.com/WezSieTato/DataDrivenTesting
  3. 确认版本并让 Xcode 解析包
  4. 在最后的对话框中,将 DataDrivenTesting 的 Add to Target 列更新为将包含数据测试的测试目标(如果你有多个测试目标,稍后可以通过手动链接其构建阶段中的库来将 DataDrivenTesting 添加到它们)。

Swift Package Manager

如果要在任何其他使用 SwiftPM 的项目中使用 DataDrivenTesting,请将该包作为 Package.swift 中的依赖项添加。

dependencies: [
  .package(
    url: "https://github.com/WezSieTato/DataDrivenTesting",
    from: "1.0.0"
  ),
]

接下来,将 DataDrivenTesting 添加为测试目标的依赖项

targets: [
  .target(name: "MyApp"),
  .testTarget(
    name: "MyAppTests",
    dependencies: [
      "MyApp",
      .product(name: "DataDrivenTesting", package: "DataDrivenTesting"),
    ]
  )
]

CocoaPods

如果要在任何其他使用 CocoaPods 的项目中使用 DataDrivenTesting,请将该包作为 Podfile 中的依赖项添加。

pod 'DataDrivenTesting', '~> 1.0'

许可证

该库是在 MIT 许可下发布的。有关详细信息,请参见 LICENSE