SwiftUI中如何对ListView的单元格值及数量进行UI测试?
iOS UI测试:访问CollectionView特定单元格的内容与索引
问题背景
我开发了一款笔记应用,在UI测试用例中添加了4条笔记(Note 1、Note 2、Note 3、Note 4),需要完成两个测试场景:
- 验证CollectionView恰好包含4个单元格(已实现)
- 验证Note 2位于第二个单元格(待实现)
现有测试代码如下:
func test_notesVew_addNewMultipleNote_shouldSeeNewNotesInHomeScreen() { let addNewButton = app.navigationBars["Notes"].buttons["Add new note button"] addNewButton.tap() let collectionViewsQuery = app.collectionViews createNote(num: 1) addNewButton.tap() createNote(num: 2) addNewButton.tap() createNote(num: 3) addNewButton.tap() createNote(num: 4) // MARK: - Scenario: Validating added notes let cellCount = collectionViewsQuery.cells.count XCTAssertEqual(cellCount, 4, "After adding 4 notes, cell count should be 4") // MARK: - Scenario: Validating note's order //let noteOnSecondRow = collectionViewsQuery.element(boundBy: 1) }
请问如何访问CollectionView特定单元格的值或索引,完成第二个测试场景?
解决方案
方法1:通过索引获取单元格,验证内容
UI测试中元素索引从0开始计数,第二个单元格对应索引1。你可以通过element(boundBy:)获取指定索引的单元格,再验证其内部的文本内容是否为Note 2:
// MARK: - Scenario: Validating note's order // 获取第二个单元格(索引1) let secondCell = collectionViewsQuery.cells.element(boundBy: 1) // 验证单元格内存在"Note 2"文本 XCTAssertTrue(secondCell.staticTexts["Note 2"].exists, "Second cell should display Note 2")
方法2:通过文本定位元素,验证其所在单元格的索引
如果需要先定位到Note 2元素,再验证它所在的单元格位置,可以这样写:
// MARK: - Scenario: Validating note's order // 定位到Note 2的文本元素 let note2Text = app.staticTexts["Note 2"] // 获取该文本所在的单元格 let note2Cell = note2Text.containing(.cell).element // 获取单元格在CollectionView中的索引 guard let note2Index = collectionViewsQuery.cells.index(of: note2Cell) else { XCTFail("Note 2 cell not found") return } // 验证索引为1(第二个位置) XCTAssertEqual(note2Index, 1, "Note 2 should be located in the second cell")
注意事项
- 确保
createNote方法正确设置了笔记单元格的文本内容,或给单元格/文本元素设置了准确的可访问性标识符(accessibilityIdentifier),这样测试才能精准定位。 - 如果CollectionView内容超出屏幕,需先调用
scrollToElement方法让目标单元格滚动到可视范围内,避免测试失败。
内容的提问来源于stack exchange,提问作者Shawkath Srijon
相关产品推荐
相关产品推荐

