javaseleniumselenium-webdriverautomation-testing

Is it better to use WebElement.isDisplayed() or WebElement.getText() and compare the results?


If I'm trying to see if a field on a web page is displaying some text, and I have the following function to dynamically do this:

public boolean isInformationFound(String info){
By infoText= By.xpath("//h5[text()='The info is:']/following::td[text()[contains(.,'"+info+"')]]");
        return findElementBy(infoText).isDisplayed();
}

and in my test case:

Assert.assertEquals(foo.isInformationFound("hello"), true)

alternatively, what I could do is:

public String getInfo(){
By infoText= By.xpath("//h5[text()='The info is:']/following::td");
        return findElementBy(infoText).getText();
}

and then in my test case function, I would do something like:

String expected info = "hello"
Assert.assertEquals(info, foo.getInfo())

Which method is better practice?


Solution

  • To assert text results, we must use getText(). The explanation is as follows:

    There are 3 methods in Selenium to check the visibility scope of an element

    1. isEnabled
    2. isDisplayed
    3. isSelected

    At times our tests fail because an element is displayed or exists in DOM, but it does not exist on the web page. So, we handle such cases by checking the visibility of the web element.

    WebDriver already has a predefined getText() method, which retrieves either the textContent (for Mozilla) or the innerText (for Chrome etc) of the element.

    Your case involves text verification so it's better to go for getText. For web element visibility verification you can use isDisplayed.