Xcode UITest 滚动到 UITableView 底部

8
我正在编写一个 UI 测试用例,在其中需要执行某个操作,然后在当前页面上将唯一的 UITableView 滚动到底部,以检查特定文本是否出现在 UITableView 的最后一个单元格中。
目前我能想到的唯一方法是使用 app.tables.cells.element(boundBy: 0).swipeUp() 进行滚动,但如果有太多单元格,则无法完全滚动到底部。而且 UITableView 中的单元格数量并不总是相同的,我不能多次向上滑动,因为表格中可能只有一个单元格。
2个回答

15
你可以通过获取tableView的最后一个单元格来实现此操作。然后,运行一个while循环,滚动并检查每个滚动时单元格isHittable是否为真。一旦确定isHittable == true,则可以对该元素进行断言。
代码示例(Swift):
  1. 在你的XCTestCase文件中,编写一个查询来识别表格。然后,编写一个后续查询来识别最后一个单元格。
https://developer.apple.com/documentation/xctest/xcuielement/1500561-ishittable
let tableView = app.descendants(matching: .table).firstMatch
guard let lastCell = tableView.cells.allElementsBoundByIndex.last else { return }
  1. 使用 while 循环来确定单元格 isHittable/是否在屏幕上。注意: isHittable 取决于单元格的 userInteractionEnabled 属性设置为 true。
//Add in a count, so that the loop can escape if it's scrolled too many times
let MAX_SCROLLS = 10
var count = 0
while lastCell.isHittable == false && count < MAX_SCROLLS {
    apps.swipeUp()
    count += 1
}

检查单元格的文本,使用

1
lastCell 存在吗?如果你的表格有 100 个单元格,那么 lastCell 是第 100 个单元格吗?还是 lastCell 是当前可见的最后一个单元格。比如第六个之类的? - Sentry.co
@Sentry.co .allElementsBoundByIndex.last 只适用于可见元素。这意味着如果您想要找到列表中的最后一个元素,而它在屏幕外,.allElementsBoundByIndex.last 将不起作用。例如:let lastCell = list.cells.allElementsBoundByIndex.last 将为您提供 list 元素中最后一个可见单元格。 我还没有找到一种适当的方法来找到列表的最后一个元素(无论是否可见)。 - undefined
是的。你必须不停地滚动直到找到最后一个。我使用这个来做:https://github.com/eonist/UITestSugar/blob/master/Sources/UITestSugar/ui/element/extension/interaction/XCUIElement%2BScroll.swift - undefined

13

Blaine的回答引导我进一步深入研究这个主题,我找到了一个不同的解决方案,适合我的情况:

func testTheTest() {
    let app = XCUIApplication()
    app.launch()

    // Opens a menu in my app which contains the table view
    app.buttons["openMenu"].tap()

    // Get a handle for the tableView
    let listpagetableviewTable = app.tables["myTableView"]

    // Get a handle for the not yet existing cell by its content text
    let cell = listpagetableviewTable.staticTexts["This text is from the cell"]

    // Swipe down until it is visible
    while !cell.exists {
        app.swipeUp()
    }

    // Interact with it when visible
    cell.tap()
}

为了使这个功能正常工作,我需要设置isAccessibilityElementtrue,并将accessibilityLabel分配给表格视图,以便在测试代码中可以查询它。

这可能不是最佳实践,但在我的测试中看起来很好用。如果单元格没有文本,可能可以通过引用图像视图或其他方式来引用单元格(这里并未直接引用)。显然,这还缺少 Blaines 回答中的计数器,但出于简单起见,我将其省略了。


1
太棒了!如果我2个小时前就找到这个,那么就可以避免很多的挫败感了。 - PakitoV
1
非常感谢您的回答,帮我节省了很多时间。 - liudasbar
这就是方法。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接