Reputation: 137
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();
}
Upvotes: 0
Views: 600
Reputation: 193308
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.
Upvotes: 1
Reputation: 2813
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 catch
you 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()
.
Upvotes: 2