expectationForPredicate 失败测试用例

expectationForPredicate Fails test case

最近开始 XCode UI 测试SWIFT。

我的问题是我需要等到元素出现在 iPhone 屏幕上。

我找到了带有“'expectationForPredicate'”和“'waitForExpectationsWithTimeout'”的解决方案,但问题在于,如果预期谓词在超时内不匹配,则此方法旨在使测试用例失败。

我需要一个可以等待元素出现在屏幕上的代码,如果元素没有出现并且超过超时,那么我不希望测试用例失败。相反,我想 return 真(元素存在)/假(不存在)

我通过避免上述函数找到了解决方案,因为这些函数未通过我的测试,而不是返回 true 或 false

下面是我创建的方法

func waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) -> Bool {
    let TIMEOUT: Double = 120 ;
    var isFound = false;
    let start = NSDate();
    var diff : Double = 0;
    repeat{
        print("Is element \(element) found : \(element.exists)")
        print("Printing debugDescription -> ")
        print(XCUIApplication().debugDescription)
        if(element.exists){
            isFound = true;
            break;
        }
        print("Waiting for element to exists... Time counter :\(diff)")
        sleep(1)
        let end = NSDate();
        diff =  end.timeIntervalSinceDate(start);
    }while(diff <= TIMEOUT);
    return isFound;
}

希望这对其他人有帮助,但如果您还有其他更好的解决方案,请在这里回答。