Ensure all 3 lines throw exception before returning true
In order for my method to return true, I need to ensure that 3 specific lines all throw an error.
try { // Wait until all three lines to throw exception Driver.FindElement(By.CssSelector(loadingTypesLock)); return false; } catch { try { Driver.FindElement(By.CssSelector(loadingTypesLock_bg)); return false; } catch { try { Driver.FindElement(By.CssSelector(loadingTypesLock_img)); return false; } catch { return true; } } }
What is the best way to do this?
Using exceptions to control program flow is generally considered bad practice. Instead, why not use the FindElements
(Selenium docs) method which returns a list of elements and then check the length of the lists?
Something like this:
return (Driver.FindElements(By.CssSelector(loadingTypesLock)).Count == 0 && Driver.FindElements(By.CssSelector(loadingTypesLock_bg)).Count == 0 && Driver.FindElements(By.CssSelector(loadingTypesLock_img)).Count == 0);
The above will return true
if the counts of the lists returned by all three methods are zero, so when no elements are found by any of them. If any of them find an element it’ll return false
.