Reputation: 1633
I have a number of tests I'm running through Selenium. Whenever one fails I just have a catch surrounding the test saying that an Element could not be found.
It seems quite vague instead I want to be able to say what element can't be found and write that to my error log. Is there a way to determine what element cannot be found?
Here is some example code I am using at the moment to catch my error.
try
{
base.SetUp();
webDriverWait.Until(ExpectedConditions.ElementToBeClickable(
excelSession.FindElementByName("Blank workbook"))).Click();
webDriverWait.Until(ExpectedConditions.ElementToBeClickable(
excelSession.FindElementByName("Create"))).Click();
webDriverWait.Until(ExpectedConditions.ElementToBeClickable(
excelSession.FindElementByName("New"))).Click();
webDriverWait.Until(ExpectedConditions.ElementToBeClickable(
excelSession.FindElementByName("E Sample Data"))).Click();
CommonMethods.IsElementDisplayed(excelSession,
new StackTrace(true).GetFrame(0).GetFileLineNumber(),
new StackTrace(true).GetFrame(0).GetMethod(), "CreateErrorIcon",
"Error appeard while selecting the E Sample Data button");
}
catch (Exception)
{
CommonMethods.ExceptionHandler("Couldn't find element",
new StackTrace(true).GetFrame(0).GetFileLineNumber(),
new StackTrace(true).GetFrame(0).GetMethod(), excelSession);
}
Upvotes: 1
Views: 56
Reputation: 7054
Declare a function that will search for elements:
Func<RemoteWebDriver, By, IWebElement> find = (driver, by) =>
{
var elements = driver.FindElements(by);
if (elements.Count < 1)
{
var msg = $"Couldn't find element {by}";
logger.Warn(msg);
throw new Exception(msg);
}
return elements.First();
};
Then use it like this:
webDriverWait.Until(
ExpectedConditions.ElementToBeClickable(
find(excelSession, By.Name("Blank workbook")))
).Click();
Upvotes: 2