Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCUITest Multiple matches found error

I am writing tests for my app and need to find the button "View 2 more offers" there are multiple of these buttons on my page but I would just like to click on one. When I try this, an error comes saying "Multiple matches found" So the question is, what ways can I go around this so my test will search and tap on only one of the buttons called "View 2 more offers".

Here is my current code

let accordianButton = self.app.buttons["View 2 more offers"]
    if accordianButton.exists {
        accordianButton.tap()
    }
    sleep(1)
}
like image 394
Billy Boyo Avatar asked Sep 12 '16 10:09

Billy Boyo


3 Answers

You should use a more elaborated way to query your button, since there is more than one button who's matching it.

    // We fetch all buttons matching "View 2 more offers" (accordianButtonsQuery is a XCUIElementQuery)
    let accordianButtonsQuery = self.app.buttons.matchingIdentifier("View 2 more offers")
    // If there is at least one
    if accordianButtonsQuery.count > 0 {
        // We take the first one and tap it
        let firstButton = accordianButtonsQuery.elementBoundByIndex(0)
        firstButton.tap()
    }

Swift 4:

    let accordianButtonsQuery = self.app.buttons.matching(identifier: "View 2 more offers")
    if accordianButtonsQuery.count > 0 {
        let firstButton = accordianButtonsQuery.element(boundBy: 0)
        firstButton.tap()
    }
like image 152
Julien Quere Avatar answered Oct 19 '22 18:10

Julien Quere


There are a couple of ways to go about solving this issue.

Absolute Indexing

If you absolutely know the button will be the second one on the screen you can access it by index.

XCUIApplication().buttons.element(boundBy: 1)

However, any time the button moves on the screen, or other buttons are added, you might have to update the query.

Accessibility Update

If you have access to the production code you can change the accessibilityTitle on the button. Change it something more specific than the title text and then access the button via test using the new title. This property only shows up for testing and won't be presented to the user when reading off the screen.

More Specific Query

If the two buttons are nested inside of other UI elements you can write a more specific query. Say, for example, that each button is inside of a table view cell. You can add accessibility to the table cells then query for the button.

let app = XCUIApplication()
app.cells["First Cell"].buttons["View 2 more offers"].tap()
app.cells["Second Cell"].buttons["View 2 more offers"].tap()
like image 11
Joe Masilotti Avatar answered Oct 19 '22 18:10

Joe Masilotti


Xcode 9 introduces a firstMatch property to solve this issue:

app.staticTexts["View 2 more offers"].firstMatch.tap()
like image 10
Xavier Lowmiller Avatar answered Oct 19 '22 18:10

Xavier Lowmiller