Craig Gallagher
Craig Gallagher

Reputation: 1633

Selenium element cannot be found error log

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.ElementTo‌​BeClickable(
      excelSession.FindElementByName("Blank workbook"))).Click();
    webDriverWait.Until(ExpectedConditions.ElementTo‌​BeClickable(
      excelSession.FindElementByName("Create"))).Click();
    webDriverWait.Until(ExpectedConditions.ElementTo‌​BeClickable(
      excelSession.FindElementByName("New"))).Click();
    webDriverWait.Until(ExpectedConditions.ElementTo‌​BeClickable(
      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

Answers (1)

Aleks Andreev
Aleks Andreev

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.ElementTo‌​BeClickable(
  find(excelSession, By.Name("Blank workbook")))
).Click();

Upvotes: 2

Related Questions