1

I've got the following situation:

I want to fill a field which is displayed some times and others don't. So, to solve this I used a if condition along with page objects.

 public static WebElement Field(WebDriver driver) {

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    WebElement element = (new WebDriverWait(driver, 9)).until(ExpectedConditions.visibilityOfElementLocated(By
        .xpath("element")));

    return element;

The if condition is:

if (PageObject.Field(driver).isDisplayed()) {
        PageObject.Field(driver).sendKeys("Lorem Ipsum Dolor");
    }

The problem is that if the field is not displayed, the script fails because the element is not found and the if condition is not used. I tried the following and didn't work either:

boolean test = driver.findElement(By.xpath("element")).isDisplayed();

    if (test) {
        PageObject.Field(driver).sendKeys("Lorem Ipsum Dolor");
    }
3

Your check needs to happen before you get to the .isDisplayed() method. The way WebDriverWait().until(ExpectedConditions.visibilityOfElementLocated()) works, it will return either the element or throw an exception.

I'd suggest something like this in your element find code:

public static WebElement Field(WebDriver driver) {

  try {
    Thread.sleep(500);
    WebElement element = (new WebDriverWait(driver, 9)).until(ExpectedConditions.visibilityOfElementLocated(By
    .xpath("element")));

    return element;
  } catch (Exception e) {
    return null;
  }

Then, in your search code:

if (PageObject.Field(driver) != null) {
  // logic for handling the field goes here
}
  • Thanks for the answers, it worked. It takes some time to check the element is not displayed (9 seconds according to my code), but even thought it is a very good solution. – alexandre.ra Feb 23 '18 at 11:46
  • How are you differentiating the case where it should be displayed but actually not displayed (defect)and vice versa? – Vishal Aggarwal Feb 23 '18 at 12:36
  • Actually I'm using only to fill some fields if they are displayed or not. To verify the condition you said "not displayed = defect" I just use the PageObject.Field(driver).isDisplayed(); and it works correctly. – alexandre.ra Feb 26 '18 at 16:07
0

Check for presence of element. Use Java's equivalent of Python's are_present(). It will return list of matching elements, empty is none are present.

  • I tried with: elementToBeClickable(locator) visibilityOfAllElementsLocatedBy(locator) presenceOfElementLocated(locator) and didn't work – alexandre.ra Feb 22 '18 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.