Mike ASP
Mike ASP

Reputation: 2333

Try block do not handle scenario when element not found

I used below code and found that TRY block is not working for the situation when element is not present :

try
{      
    var actual = new WebDriverWait(m_WebDriver, TimeSpan
        .FromSeconds(5))
        .Until(ExpectedConditions
        .ElementIsVisible(By.XPath(XpathUnderTest)))
        .Displayed;

    return actual;
}
catch (Exception ex)
{      
   return false;
}

I have a use-case where presence of Webelement is depend on other conditions so it is not present or visible all the time on webpage. If element is present then it's working and if element is not present then Try catch is not able to handle the scenario using you above code.

I also tried : bool isPresent = Driver.Findelements.(xpath).Count() > 0; // list but it is not working as well if element is not present

Upvotes: 1

Views: 726

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193058

As per your code block it's the right behavior as WebDriverWait with ElementIsVisible is correct.

As per the documentation, ExpectedConditions with ElementIsVisible will return the IWebElement once it is located and visible. In case the ExpectedConditions fails a Boolean value is returned back.

As in your try block you are defining :

var actual;

And trying to :

return actual;

So, irespective of the return from ExpectedConditions with ElementIsVisible your try block returns False Positive.

Solution :

WebDriverWait with ExpectedConditions must be implemented outside any Try-Catch block. Next steps can be decided with respect to the return type.

Upvotes: 1

Related Questions