1

I faced the next problem:

Code Sample:

if (!driver.isElementPresent(By.id("intentionally_wrong_ID"))) {

    collector.addError(new Throwable("Error: *"+PDS_lbl_txt+"* label not found on page."));

} else {

    collector.checkThat(PDS_lbl.getText(), equalTo(PDS_lbl_txt));
}

The sample above works as expected:

java.lang.Throwable: Error: *Dispense System* label not found on page.

But when I tried to use String variable in By.id statement the IF condition doesn't work when script is running:

String dispSys = "intentionally_wrong_ID";

    if (!driver.isElementPresent(By.id(dispSys))) {

    collector.addError(new Throwable("Error: *"+PDS_lbl_txt+"* label not found on page."));

} else {

    collector.checkThat(PDS_lbl.getText(), equalTo(PDS_lbl_txt));
}

Result:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"intentionally_wrong_ID"}
Command duration or timeout: 11.78 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'

driver.isElementPresent(By) is custom method but there is nothing wrong with it. I also tried driver.findElements native method with the same result:

String dispSys = "intentionally_wrong_ID";

    if (driver.findElements(By.id(dispSys)).size() < 1) {

    collector.addError(new Throwable("Error: *"+PDS_lbl_txt+"* label not found on page."));

} else {

    collector.checkThat(PDS_lbl.getText(), equalTo(PDS_lbl_txt));
}

I would be very appreciated if you give me a clue how to work it out. Thank you.

Biffen
  • 6,249
  • 6
  • 28
  • 36

1 Answers1

1

You can rewrite your isElementPresent to something like this:

public boolean isElementPresent(String elementId) {
    try {
        driver.findElement(By.id(elementId)).isDisplayed();
        return true;
    } catch (NoSuchElementException ignored) {
        return false;
    }
}
  • Thank you for the answer but 'isElementPresent' is not a point here. Also, I 'm not a big fan of '.isDisplayed()' for some reasons (like this http://stackoverflow.com/questions/24946703/selenium-webdriver-using-isdisplayed-in-if-statement-is-not-working). The point is I don't get it why the way I stored ID affected IF statement. – Ivan Litskevich May 12 '15 at 17:25