我们有一个使用XCTest编写的后端测试套件。该套件在Xcode中运行良好,但出于各种原因,如果我们也能在iOS应用程序中运行该套件,那将是很好的。这是否可能?我不介意为此编写一些粘合代码,但目前我甚至无法在非测试目标中导入XCTest框架:
SomeController.swift:2:8: Cannot load underlying module for 'XCTest'
我们有一个使用XCTest编写的后端测试套件。该套件在Xcode中运行良好,但出于各种原因,如果我们也能在iOS应用程序中运行该套件,那将是很好的。这是否可能?我不介意为此编写一些粘合代码,但目前我甚至无法在非测试目标中导入XCTest框架:
SomeController.swift:2:8: Cannot load underlying module for 'XCTest'
可以实现!关键是要获得XCTest框架链接的副本,然后使用公共的XCTest API运行您的测试。这将给您与在Xcode中运行测试时看到的相同的控制台输出。使用公共API连接自己的自定义报告器似乎是可行的,但如何执行这样的操作是一个好问题 - 不多人使用XCTest API,因为Xcode已经为我们完成了繁重的工作。
与其解开模块加载过程中的问题,不如从目标平台的平台框架中将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/
接下来,打开你主应用程序目标的编辑器,将从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
cp -Rp \ "$PLATFORMS/iPhoneSimulator.platform/$FRAMEWORKS/../PrivateFrameworks/XCTAutomationSupport.framework" \ Frameworks/iphonesimulator/
并且也可以拖放“XCTAutomationSupport.framework”。 - kanobius