获取在 Xcode UI 测试中执行的每个测试用例的结果

Get result of each test case executed in Xcode UI tests

我需要在 Xcode 的测试套件中执行每个测试用例后的测试状态。我知道观察者可以帮助实现它。但是如何在我的测试中使用它呢?

执行的每个测试用例的结果保存在名为 ***TestSummeries.plist 的文件中。

您会在

下找到它
~/Library/Developer/Xcode/DerivedData/<your-app-name>/Logs/Test/****_TestSummeries.plist

如果您 运行 多次测试,只需在执行前删除 DerivedData 中的所有内容。那么你会发现只有一个 TestSummeries.plist.

然后解析plist并从plist文件中获取你想要的数据。

** 如果您需要更多信息,请随时在下面发表评论。

您走在正确的轨道上,可以通过 XCTestObservation 协议 (https://developer.apple.com/documentation/xctest/xctestobservation) 实现您想做的事情。您可以在测试用例中添加一个观察者 class,我建议在 setUp() 方法中执行此操作,因为它会在每个测试方法之前执行。

override func setUp() {
    super.setUp()

    continueAfterFailure = false

    XCUIApplication().launch()

    XCTestObservationCenter.shared.addTestObserver(UITestObserver())
}

为此,您应该实现一个符合 XCTestObservation 协议的 class,然后向感兴趣的方法提供您自己的实现,以执行您 need/want 的任何操作。在您的情况下,您可能想要为此方法提供一个实现...

optional public func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: Int)

这里是这个测试观察者 class 可能看起来像的一个简单示例...

import XCTest

public class UITestObserver: NSObject, XCTestObservation {
    public func testCase(_ testCase: XCTestCase,
                           didFailWithDescription description: String,
                           inFile filePath: String?,
                           atLine lineNumber: Int) {
        print("failure description: \(description)")
        print("failed test case: \(testCase)")
        if let filePath = filePath {
            print("failure at file path: \(filePath)")
        }
        print("failure at line: \(lineNumber)")
    }
}

我在上面的示例中提供的这个函数会在您的一个测试用例失败时被调用,因此您不需要 "do" 测试用例 class 或方法中的任何内容。

希望对您有所帮助!