MKAnnotation 通过 XCTest UI 测试

MKAnnotation via XCTest UI Testing

如何通过 XCTest 的 UI 测试访问 MKMapView 上的引脚?

我想计算数量,验证是否有特定的(基于可访问性 ID 或标题)等

MKAnnotation 似乎没有 XCUIElementType。

我很难找到有关 MKMapView + XCTest 的任何文档。

使用UIAccessibilityIdentification.

class Annotation: NSObject, MKAnnotation, UIAccessibilityIdentification {
    let coordinate: CLLocationCoordinate2D
    let title: String?
    var accessibilityIdentifier: String?

    init(title: String?, coordinate: CLLocationCoordinate2D) {
        self.title = title
        self.coordinate = coordinate
    }
}

let coordinate = CLLocationCoordinate2DMake(40.2853, -73.3382)
let annotation = Annotation(title: "A Place Title", coordinate: coordinate)
annotation.accessibilityIdentifier = "Some Identifier"
let mapView = MKMapView()
mapView.addAnnotation(annotation)

正在测试中,您可以通过 otherElements 引用注释。

let app = XCUIApplication()
let annotation = app.maps.element.otherElements["Custom Identifier"]
annotation.tap()

很遗憾,注释视图不在 maps 下。相反,您会在那里找到地图上的兴趣点。要查询注释视图,您应该使用 XCUIApplication().windows.element.otherElements["Custom Identifier"].

accessibilityIdentifier = "Custom Identifier" 添加到您的注释 查看 ,而不是注释。 MKAnnotation 没有实现 accessibilityIdentifier.

在我的地图中,我只有 1 个引脚,我可以使用 地图引脚 标识符访问它,如下所示:

    let annotation = app.otherElements.matching(identifier: "Map pin").firstMatch
    XCTAssertTrue(annotation.exists)

    annotation.tap()