在一个只包含 20 行 TableView 的应用程序中,所有这些都包含文本“Cell X”,X 是该行的索引,我有以下测试:
func testTwentyFirstRow()
{
let cell = XCUIApplication().staticTexts["Cell 20"]
let label = cell.label
XCTAssert(label == "Cell 20", "Label is not equal to Cell 20")
}
此测试在第二行失败并出现以下错误
No matches found for Find: Elements matching predicate '"Cell 20" IN identifiers' from input {(
StaticText, 0x60800019b930, traits: 8589934656, label: 'Cell 0',
...
StaticText, 0x60800019d740, traits: 8589934656, label: 'Cell 19'
)}
是否有任何方法可以防止它在那里失败,但让它在下一行而不是我断言标签值的地方失败?
最佳答案
如果您访问 XCUIElement 的属性而不是 exists
,框架将尝试解析导致该元素的查询,然后检查它以找到该属性的值。
如果您在检查任何其他元素或与其交互之前检查元素存在
,则可以处理该元素尚不存在的情况。
if cell.exists {
let label = cell.label
XCTAssertEqual(label, "text")
} else {
XCTFail("Cell did not exist")
}
此时您不必通过测试,您可以采取行动使单元格存在,使用循环继续滚动直到它确实存在,或者您喜欢的任何方式。
关于swift - 防止访问不存在的元素导致测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157465/