如何将私有函数变成辅助函数?

How to make a private function into a helper function?

我一直在为我的应用编写测试。但是,当 运行 我的测试时,我的函数

不断出现错误 Stall on main thread
private func waitForElementToAppear(testCase: XCTestCase,
                                    element: XCUIElement,
                                    file: String = #file,
                                    line: UInt = #line) {

    let existsPredicate = NSPredicate(format: "exists == true")
    testCase.expectationForPredicate(existsPredicate,
                                     evaluatedWithObject: element, handler: nil)

    testCase.waitForExpectationsWithTimeout(5) { (error) -> Void in
        if (error != nil) {
            let message = "Failed to find \(element) after 5 seconds."
            testCase.recordFailureWithDescription(message,
                                                  inFile: file, atLine: line, expected: true)
        }
    }
}

我在 tests/code 中多次使用此功能。我怎样才能把它转换成一个辅助函数,所以我只需要写一次这个函数。提前感谢您的帮助:)

您可以创建一个帮助程序 class 并将函数设为静态

class Helper {
    static func waitForElementToAppear(testCase: XCTestCase,
                                element: XCUIElement,
                                file: String = #file,
                                line: UInt = #line) {
        // do stuff
    }
}

这样,无论您需要使用该函数,都可以在 helper 上调用该函数。

使用扩展更快捷:

extension XCTestCase {

    // your function here
}

因此您可以在所有测试中使用它 classes 而无需额外的 class