MKAnnotation via XCTest UI Testing

1.4k Views Asked by At

How can I access the pins on an MKMapView via XCTest's UI Tests?

I want to count the number, verify specific ones are there (based on accessibility id or title), etc.

There doesn't seem to be a XCUIElementType for MKAnnotation.

I'm having a hard time finding any documentation on MKMapView + XCTest.

3

There are 3 best solutions below

1
On BEST ANSWER

The annotation views aren't under maps unfortunately. You will find map points of interest there instead. To query for an annotation view you should use XCUIApplication().windows.element.otherElements["Custom Identifier"].

Add the accessibilityIdentifier = "Custom Identifier" to your annotation view, not annotation. MKAnnotation doesn't implement accessibilityIdentifier.

1
On

Use 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)

Under test you can reference the annotation via otherElements.

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

In my map i had only 1 pin and i could access to it with Map pin identifier like this:

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

    annotation.tap()