有可能!关键是获取 XCTest 框架链接的副本,然后使用公共 XCTest API 运行测试。这将为您提供通过 Xcode 运行测试时看到的相同控制台输出。 (使用公共 API 连接您自己的自定义报告器看起来是可行的,但询问如何这样做本身就是一个好问题 - 使用 XCTest API 的人并不多,因为 Xcode 为我们完成了繁琐的工作。)
在 XCTest.framework 中复制
您可以从目标平台的平台框架中将 XCTest.framework 包复制到您的项目中,而不是解开任何破坏模块加载的问题:
mkdir Frameworks && mkdir Frameworks/iphonesimulator
PLATFORMS=/Applications/Xcode.app/Contents/Developer/Platforms
FRAMEWORKS=Developer/Library/Frameworks
cp -Rp \
"$PLATFORMS/iPhoneSimulator.platform/$FRAMEWORKS/XCTest.framework" \
Frameworks/iphonesimulator/
链接到您自己的 XCTest
然后,弹出打开主应用目标的目标编辑器,然后将副本从 Finder 拖放到“链接框架和库”列表中。
将您的测试构建到主应用目标中
现在,转到您的测试文件,弹出文件检查器,然后勾选这些文件的主应用目标旁边的框。现在,您正在构建测试文件作为主应用程序的一部分,这会将所有 XCTestCase 子类放入二进制文件中。
运行这些测试
最后,将“运行测试”按钮连接到如下操作:
import UIKit
import XCTest
class ViewController: UIViewController {
@IBAction func runTestsAction() {
print("running tests!")
let suite = XCTestSuite.default()
for test in suite.tests {
test.run()
}
}
}
当您点击按钮时,您会在控制台中看到:
running tests!
Test Suite 'RunTestsInApp.app' started at 2017-05-15 11:42:57.823
Test Suite 'RunTestsInAppTests' started at 2017-05-15 11:42:57.825
Test Case '-[RunTestsInApp.RunTestsInAppTests testExample]' started.
2017-05-15 11:42:57.825 RunTestsInApp[2956:8530580] testExample()
Test Case '-[RunTestsInApp.RunTestsInAppTests testExample]' passed (0.001 seconds).
Test Case '-[RunTestsInApp.RunTestsInAppTests testPerformanceExample]' started.
/Users/jeremy/Workpad/RunTestsInApp/RunTestsInAppTests/RunTestsInAppTests.swift:34: Test Case '-[RunTestsInApp.RunTestsInAppTests testPerformanceExample]' measured [Time, seconds] average: 0.000, relative standard deviation: 122.966%, values: [0.000002, 0.000001, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
Test Case '-[RunTestsInApp.RunTestsInAppTests testPerformanceExample]' passed (0.255 seconds).
Test Suite 'RunTestsInAppTests' passed at 2017-05-15 11:42:58.081.
Executed 2 tests, with 0 failures (0 unexpected) in 0.256 (0.257) seconds
Test Suite 'RunTestsInApp.app' passed at 2017-05-15 11:42:58.081.
Executed 2 tests, with 0 failures (0 unexpected) in 0.256 (0.258) seconds