【问题标题】:Wait until object is not visible on the screen using Swift and XCTest使用 Swift 和 XCTest 等到对象在屏幕上不可见
【发布时间】:2016-09-23 15:28:56
【问题描述】:

我正在寻求帮助来编写一个等待指定元素不再出现在页面上的方法。我正在使用 Swift 2.2 和 XCTest 进行开发。如您所见,我是这里的新手,也是编程新手。非常感谢您的帮助。

【问题讨论】:

    标签: swift xctest xcode-ui-testing xctestexpectation


    【解决方案1】:

    您可以通过XCUIElement.exists 每秒检查元素 10 秒,然后断言该元素。 ActivityIndi​​cator 参见以下内容:

    public func waitActivityIndicator() {
        var numberTry = 0
        var activityIndicatorNotVisible = false
        while numberTry < 10 {
            if activityIdentifier.exists {
                sleep(1)
                numberTry += 1
            } else {
                activityIndicatorNotVisible = true
                break
            }
        }
        
        XCTAssert(activityIndicatorNotVisible, "Activity indicator is still visible")
    }
    

    【讨论】:

      【解决方案2】:

      为此,我在XCUIElement 上写了一个超级简单的waitForNonExistence(timeout:) 扩展函数,它反映了现有的XCUIElement.waitForExistence(timeout:) 函数,如下:

      extension XCUIElement {
      
          /**
           * Waits the specified amount of time for the element’s `exists` property to become `false`.
           *
           * - Parameter timeout: The amount of time to wait.
           * - Returns: `false` if the timeout expires without the element coming out of existence.
           */
          func waitForNonExistence(timeout: TimeInterval) -> Bool {
          
              let timeStart = Date().timeIntervalSince1970
          
              while (Date().timeIntervalSince1970 <= (timeStart + timeout)) {
                  if !exists { return true }
              }
          
              return false
          }
      }
      

      【讨论】:

        【解决方案3】:

        您必须为要测试的条件设置谓词:

        let doesNotExistPredicate = NSPredicate(format: "exists == FALSE")
        

        然后为您的测试用例中的谓词和 UI 元素创建一个期望:

        self.expectationForPredicate(doesNotExistPredicate, evaluatedWithObject: element, handler: nil)
        

        然后等待你的期望(指定超时,如果不满足期望,测试将失败,这里我使用5秒):

        self.waitForExpectationsWithTimeout(5.0, handler: nil)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-16
          相关资源
          最近更新 更多