0

I am using if block to check if product is in stock or out of stock. but it is not executing the else block , also I don't want to put else part in catch block.

I have used isDisplayed, isEnabled but still it is not working.

try {
    if (driver.findElement(By.xpath("//span[contains(text(),'Currently unavailable.')]"))
            .isEnabled()) {
        o1.put("STOCK", "Out of Stock");
    } else {
        o1.put("STOCK", "In Stock");
    }
} catch (NoSuchElementException e) {
    e.printStackTrace();
}
jhamon
  • 3,603
  • 4
  • 26
  • 37
Anuj Bansal
  • 117
  • 5

2 Answers2

2

It is recommended to use findElements() method whenever checking for presence of element because if timeout occurs it will return empty list instead exception and you are saved from handling the exception in case of findElements(). So remove the try catchyou don't need it with below code.

if(driver.findElements(By.xpath("//span[contains(text(),'Currently unavailable.')]")).size() > 0) {
    o1.put("STOCK", "Out of Stock");
} else {
    o1.put("STOCK", "In Stock");
}

As you have mentioned in your code in if condition, it will always raise exception if element it not found before reaching to the method .isEnabled().

Dev
  • 2,739
  • 2
  • 21
  • 34
1

To check the condition you need to check the visibility of the element, so, instead of using isDisplayed() and isEnabled() you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use the following Locator Strategy:

try {
    new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(text(),'Currently unavailable.')]")));
    o1.put("STOCK", "Out of Stock");
} catch (TimeoutException e) {
    o1.put("STOCK", "In Stock");
}

Note: If you are using try-catch {} block, you don't need if-else {} block which will be an overhead.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352