Search code examples
javaappium

Appium find element by 2 parameters in Java


I use Appium with Java to automate tests for mobile application. I'm looking for a way to find element by 2 parameters. I.e. by accessibilityId and by xPath within this element. So really rough example to visualize what I mean

Element el = driver.findElementByAccessibilityId("name").isDisplayed();
Assert.assertTrue(el.findElement(By.xPath("//android.widget.TextView[@text='texty']")));

Is this correct way to do this? Is there a better way? Ideal would be one liner because it is easier to understand


Solution

  • isDisplayed() does not return MobileElement/WebElement it returns a Boolean so a valid way is something like mentioned below

    WebElement el = driver.findElementByAccessibilityId("name");
    if (e1.isDisplayed()){
       WebElement e2 = el.findElement(By.XPath("//android.widget.TextView[@text='texty']"))
    }
    Assert.assertTrue(e2.isDisplayed());
    

    You can chain any number of findElement e.g.

    WebElement innerElement = 
          driver.findElement(By.AccessbilityID("someID"))
                .findElement(By.xpath("someXpath"))
                .findElement(By.cssSelector(".aValidCSSClass"));
    

    If you use findElements you have to use it like this as it return List of WebElement or List of MobileElement

    WebElement innerElement = 
          driver.findElements(By.AccessbilityID("someID"))
                .get(2)  //get 2nd element
                .findElements(By.xpath("someXpath"))
                 .get(1) //get 1st element
                .findElement(By.cssSelector(".aValidCSSClass"));