我目前正在开发一个包含许多异步代码的项目,并且正在为这个项目编写 UITests。在开发过程中,我一个一个地运行它们,但从未在一个组中运行。所以我认为测试成功了。但是当一起测试它们时,它们中的大多数都失败了。我正确实施了设置和拆卸。我研究了这种行为的原因,但我找不到任何好的答案来解决这个问题。这就像等待期望没有正常工作......
这是导致大多数问题的方法。每次我想等待一个元素出现时,我都会调用它。
/*
* This method will wait for an element (10 seconds default) afterwards it will assert it existence
*
* - parameter toAppear:The condition we are waiting for.
* - parameter element: The element to be expected
* - parameter timeout: The MAX time that the function will wait for the element, 10 seconds if none is given
* - parameter file: The file where the error will be displayed, the current file will be used in case none is provided
* - parameter line: The code line where the error will be displayed, the current line will be used in case none is provided
*/
static func assertForElement(toAppear: Bool, _ element: XCUIElement?, timeout: TimeInterval = 10, file: String = #file, line: Int = #line) {
guard let currentTestCase = BaseXCTestCase.CurrentTestCase else {
return
}
guard let element = element else {
let message = "Element cannot be empty"
currentTestCase.recordFailure(withDescription: message, inFile: file, atLine: line, expected: true)
return
}
let existsPredicate = NSPredicate(format: "exists == \(toAppear)")
currentTestCase.expectation(for: existsPredicate, evaluatedWith: element, handler: nil)
currentTestCase.waitForExpectations(timeout: timeout) { [weak currentTestCase] (error: Error?) in
if (error != nil) {
let appearMessage = "Failed to find \(String(describing: element)) after \(timeout) seconds."
let disappearMessage = "Failed to see \(String(describing: element)) disappear after \(timeout) seconds."
currentTestCase?.recordFailure(withDescription: ((toAppear == false) ? disappearMessage : appearMessage), inFile: file, atLine: line, expected: true)
}
}
}
有没有人有 UITest 异步代码的好方法?
非常感谢您!
更新
这是我收到的错误警告。
大多数时候我只是得到:Asynchronous wait failed: Exceeded timeout of 10 seconds, with unfulfilled expectations: "Expect predicate
exists == 1for object
但该元素在模拟器中是可见和可点击的。另一方面,我得到:caught "NSInternalInconsistencyException", "API violation - creating expectations while already in waiting mode."
...