0

背景

以下测试调用作为 XCTestCase 扩展的方法。目标:

  • waitForElementExists方法返回,因为元素存在或
  • waitForElementExists方法使调用它的测试用例/setUp 方法失败,因为该元素在指定时间内不存在

UI Automation XCTestCase 扩展等待方法:

extension XCTestCase
{
    /**
    Wait for the view to load
    Note: Must be a part of XCTestCase in order to utilize expectationForPredicate and waitForExpectationsWithTimeout

    - Parameter
    - element:    The XCUIElement representing the view
    - timeout: The NSTimeInterval for how long you want to wait for the view to be loaded
    - file: The file where this method was called
    - line: The line where this method was called
    */
    func waitForElementExists(element: XCUIElement, timeout: NSTimeInterval = 60,
                       file: String = #file, line: UInt = #line)
    {
        let exists = NSPredicate(format: "exists == true")

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

waitForExpectationsWithTimeout 正常工作的示例

测试用例

override func setUp()
{
    super.setUp()

    // Stop immediately when a failure occurs.
    continueAfterFailure = false

    XCUIApplication().launch()

    waitForElementExists(XCUIApplication().buttons["Foo"])
}

func testSample()
{
    print("Success")
}

这行得通!testSample永远不会被调用。

但是,如果我们将 waitForElementExists 调用移至辅助方法会怎样?

waitForExpectationsWithTimeout 成功返回但不应该返回的示例

在这里,测试用例继续进行,就好像断言从未发生过一样。如果我在 中设置断点waitForElementExists,我会看到它continueAfterFailure设置为 true,因此很明显它没有连接到与主测试用例相同的代码。

测试用例

lazy var SomeHelper = SomeHelperClass()

override func setUp()
{
    super.setUp()

    // Stop immediately when a failure occurs.
    continueAfterFailure = false

    XCUIApplication().launch()

    SomeHelper.waitForReady()

}

func testSample()
{
    print("Success")
}

帮助文件

class SomeHelperClass: XCTestCase
{
    /**
    Wait for the button to be loaded
    */
    func waitForReady()
    {
        waitForElementExists(XCUIApplication().buttons["Foo"])
    }
}
4

1 回答 1

0

由于您的助手类是 XCTestCase 的子类,因此它有自己的continueAfterFailure属性,默认情况下为 true。

如果你想要一个辅助类,它不应该来自 XCTestCase,因为 XCTestCase 子类应该实现测试方法。如果您需要从帮助程序类中的 XCTestCase 扩展访问功能,请在创建帮助程序类时通过组合传递您的测试用例对象。

class SomeHelper {

  let testCase: XCTestCase

  init(for testCase: XCTestCase) {
    self.testCase = testCase
  }

  func await(_ element: XCUIElement) {
    testCase.waitForElementExists(element)
  }

}

class MyTests: XCTestCase {

  let app = XCUIApplication()
  var helper: SomeHelper!

  func setUp() {
    continueAfterFailure = false
    helper = SomeHelper(for: self)
    helper.await(app.buttons["foo"])
  }

}
于 2016-10-21T22:58:25.713 回答