Xcode UI 测试:UITableViewCell 上的辅助功能查询失败

Xcode UI test : Accessibility query fail on UITableViewCell

问题

使用Xcode UI测试,我无法查询UITableView

中的单元格

解释

UITableView

UITableView 包含 3 个单元格:

import UIKit

@objc class DumpTable: UITableViewController {
    var objects: [NSDate] = [NSDate]()

    override func viewDidLoad() {
        super.viewDidLoad()

        objects.append(NSDate())
        objects.append(NSDate())
        objects.append(NSDate())

        tableView.isAccessibilityElement = true
        tableView.accessibilityLabel = "Thetable"
        tableView.accessibilityIdentifier = "Thetable"
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell()

        let object = objects[indexPath.row]
        cell.textLabel!.text = object.description

        cell.isAccessibilityElement = true
        cell.accessibilityLabel = "Thecell"
        cell.accessibilityIdentifier = "Thecell"

        return cell
    }
}

测试

测试真的很简单

给定一个包含 3 个单元格的 UITableView,我试图断言是否有可用的单元格:

XCTAssertTrue(XCUIApplication().tables["Thetable"].exists)
XCTAssertTrue(XCUIApplication().tables["Thetable"].cells.count > 0)

然后它将在 2 个断言上失败:

Assertion Failure: XCTAssertTrue failed - 
/Users/damiengavard/Desktop/Table/TableUITests/TableUITests.swift:33: error: -[TableUITests.TableUITests testExample] : XCTAssertTrue failed - 

如何重现

https://github.com/dagio/TableCellAccessibility

直接执行Cmd+U

我找到了答案here。为了使 UITableViewCell 可访问,包含 UITableView 本身不能访问。

因此,您只需删除这些行:

tableView.isAccessibilityElement = true
tableView.accessibilityLabel = "Thetable"
tableView.accessibilityIdentifier = "Thetable"

在您的示例项目中,您要在 table 中寻找 table。

let tableView = XCUIApplication().tables.containingType(.Table, identifier: "Thetable")

您应该使用 matchingIdentifier:,它搜索屏幕上的 table,而不是 containingType:identifier:,它搜索 后代 的 table 屏幕上。