背景
以下测试调用作为 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"])
}
}