Reputation: 55
I have a page where I can have items."Select all" button is visible only if items exist and there is not "Select all" button if there are no items. I have code to click "Select all" if I have items (button exists) and redirect if items count==0 (button doensn't exist):
public void ClickSelectAllItemsButton()
{
IWebElement element = driver.FindElement(By.XPath("select-all"));
if (element.Enabled && element.Displayed)
{
element.Click();
}
else {
Thread.Sleep(2000);
driver.Navigate().GoToUrl("https://some-url.com");
}
}
This code work fine if there are some items but if I have 0 items, my test fails because 'else' block is not working. What am I doing wrong? p.s. Webdriver is working fine and there is no compile errors
Upvotes: 1
Views: 265
Reputation: 33361
In case there is no "Select all" element driver.FindElement(By.XPath("select-all"))
throws exception.
There are several ways to fix this. The simplest is to use driver.FindElements
since it returns a list of web elements. In case element exists the list is not empty, otherwise it returns an empty list.
So we can check if the list is empty or not as following:
public void ClickSelectAllItemsButton()
{
var elements = driver.FindElements(By.XPath("select-all"));
if (elements.Count>0 && elements[0].Enabled && elements[0].Displayed)
{
elements[0].Click();
}
else {
Thread.Sleep(2000);
driver.Navigate().GoToUrl("https://some-url.com");
}
}
Upvotes: 1