是否有可能在iOS应用程序中运行XCTesttesting?

我们有一个用XCTest编写的后端testing套件。 该套件在Xcode中运行良好,但由于各种原因,如果我们也可以在iOS应用程序中运行该套件,那将会是一件好事。 那可能吗? 我不介意为它写一些胶水代码,但因为它是我甚至不能导入XCTest框架在一个非testing目标:

SomeController.swift:2:8: Cannot load underlying module for 'XCTest' 

有可能的! 关键是获得XCTest框架的副本,然后使用公共XCTest API来运行testing。 这将给你通过Xcode运行testing时看到的相同的控制台输出。 (使用公共API编写自己的自定义logging器看起来是可行的,但是询问如何这样做本身就是一个很好的问题 – 没有多less人使用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

然后,为主要应用程序目标popup打开目标编辑器,并将您的副本从Finder拖放到“链接的框架和库”列表中。

build立你的testing到主要的应用程序目标

现在,转到您的testing文件,popup打开文件检查器,并勾选这些文件的主要应用程序目标旁边的框。 现在,您将构buildtesting文件作为主应用程序的一部分,将所有XCTestCase子类放入二进制文件中。

运行这些testing

最后,将一个button连接到“运行testing”以执行如下操作:

 import UIKit import XCTest class ViewController: UIViewController { @IBAction func runTestsAction() { print("running tests!") let suite = XCTestSuite.default() for test in suite.tests { test.run() } } } 

当你点击button,你会看到在控制台中:

 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