UITesting Xcode 7:如何判断XCUIElement是否可见?

时间:2015-10-01 15:31:39

标签: swift automation xcode7 ui-testing xcode-ui-testing

我正在使用Xcode 7中的UI测试自动化应用程序。我有一个带有XCUIElements(包括按钮等)的滚动视图。有时XCUIElements是可见的,有时它们在scrollview上隐藏得太远(取决于我在scrollview上的位置)。

有没有办法将项目滚动到视图中,或者可以判断它们是否可见?

由于

5 个答案:

答案 0 :(得分:14)

很遗憾Apple尚未在scrollTo上提供任何.visible方法或XCUIElement参数。也就是说,您可以添加几个辅助方法来实现某些功能。以下是我在Swift中的表现。

首先检查元素是否可见:

func elementIsWithinWindow(element: XCUIElement) -> Bool {
    guard element.exists && !CGRectIsEmpty(element.frame) && element.hittable else { return false }
    return CGRectContainsRect(XCUIApplication().windows.elementBoundByIndex(0).frame, element.frame)
}

不幸的是,如果元素已加载但不在屏幕上,.exists将返回true。另外,我们必须检查目标元素的框架是否大于0乘0(有时也是如此) - 然后我们可以检查这个框架是否在主窗口内。

然后我们需要一种向上或向下滚动可控量的方法:

func scrollDown(times: Int = 1) {
    let topScreenPoint = app.mainWindow().coordinateWithNormalizedOffset(CGVector(dx: 0.5, dy: 0.05))
    let bottomScreenPoint = app.mainWindow().coordinateWithNormalizedOffset(CGVector(dx: 0.5, dy: 0.90))
    for _ in 0..<times {
        bottomScreenPoint.pressForDuration(0, thenDragToCoordinate: topScreenPoint)
    }
}

func scrollUp(times: Int = 1) {
    let topScreenPoint = app.mainWindow().coordinateWithNormalizedOffset(CGVector(dx: 0.5, dy: 0.05))
    let bottomScreenPoint = app.mainWindow().coordinateWithNormalizedOffset(CGVector(dx: 0.5, dy: 0.90))
    for _ in 0..<times {
        topScreenPoint.pressForDuration(0, thenDragToCoordinate: bottomScreenPoint)
    }
}  

更改topScreenPoint和bottomScreenPoint的CGVector值将更改滚动操作的比例 - 请注意,如果您太靠近屏幕边缘,则会拉出其中一个OS菜单。

使用这两种方法,您可以编写一个循环,以一种方式滚动到给定的阈值,直到元素变为可见,然后如果它找不到它的目标,则滚动另一种方式:

func scrollUntilElementAppears(element: XCUIElement, threshold: Int = 10) {
    var iteration = 0

    while !elementIsWithinWindow(element) {
        guard iteration < threshold else { break }
        scrollDown()
        iteration++
    }

    if !elementIsWithinWindow(element) { scrollDown(threshold) }

    while !elementIsWithinWindow(element) {
        guard iteration > 0 else { break }
        scrollUp()
        iteration--
    }
}

这最后一种方法效率不高,但它至少可以让你在屏幕上找到元素。当然,如果您知道在给定测试中您的目标元素总是高于或低于您的起点,那么您可以在此处编写scrollDownUntilscrollUpUntill方法而不使用阈值逻辑。 希望这有帮助!

答案 1 :(得分:5)

我必须做的就是在我的UI测试代码中实际向上或向下滑动。你试过这个吗?

XCUIApplication().swipeUp()

或者你也可以做WhateverUIElement.swipUp(),它会相对于那个元素向上/向下滚动。

希望他们能够修复自动滚动或自动查找功能,因此我们不必手动执行此操作。

答案 2 :(得分:2)

您应该检查isHittable属性。

如果未隐藏视图,则相应的XCUIElement是可命中的。但有一点需要注意。 &#34;查看1&#34;可以通过&#34; View 2&#34;重叠,但是对应于&#34; View 1&#34;可以打到。

答案 3 :(得分:2)

由于你在桌面视图的底部有一些XCUIElements(表格页脚视图),在UI测试中滚动tableview一直到底部的方式,假设你的tableview有很多数据,是{{1 }}

tap()也可以完成这项任务,但问题是当你的测试数据很大时,需要永远滑动,而不是直接跳转到tableView底部的.swipeUp()

更特别地说:

.tap()

答案 4 :(得分:0)

看起来这是一个已知的错误: - (

https://forums.developer.apple.com/thread/9934

相关问题