Question

I am currently assisting in a proof of concept using Selenium 2 / WebDriver with C# against an ASP.NET MVC application using the InternetExplorerDriver.

The application uses a standard pattern for notifying users that a record has saved. This works by settings TempData to include "Record saved successefully", and if TempData is present in the View, the view will alert the message.

Whilst working on Selenium tests for this functionality, we are receiving inconstitant behaviour from the below C# / Selenium test code:

        _driver.Navigate().GoToUrl(_baseUrl + "/Amraam/List");
        _driver.FindElement(By.LinkText("Create New")).Click();

        _driver.FindElement(By.Id("txtAmraamSerialNumber")).SendKeys("CC12345");

        var selectElement = new SelectElement(_driver.FindElement(By.Id("LocationId")));
        selectElement.SelectByText("Tamworth");
        _driver.FindElement(By.Id("btnSave")).Click();
        var wait = new WebDriverWait(_driver, defaultTimeout);
        IAlert alert = wait.Until(drv => drv.SwitchTo().Alert());
        _alertText = alert.Text;

        alert.Accept();
        Assert.That(_alertText, Is.EqualTo("Record successfully saved")); 

Approximately 50% of the time, Selinium will fail with a

OpenQA.Selenium.NoAlertPresentException : No alert is active

I struggle to find an exact way to replicate the issue, and worry regarding the inconsistency aspect. If it failed consistently, then we could debug and track the problem down.

Was it helpful?

Solution

The handling of alerts and prompts within Selenium 2 is pretty new and is still under active development. Your failures are probably due to timing, so I would suggest writing a wrapper method around the call to SwitchTo().Alert() so that you catch the OpenQA.Selenium.NoAlertPresentException and ignore it until the timeout expires.

Something as simple as this should work:

private IAlert AlertIsPresent(IWebDriver drv)
{
    try
    {
        // Attempt to switch to an alert
        return drv.SwitchTo().Alert();
    }
    catch (OpenQA.Selenium.NoAlertPresentException)
    {
        // We ignore this execption, as it means there is no alert present...yet.
        return null;
    }

    // Other exceptions will be ignored and up the stack
}

This line

IAlert alert = wait.Until(drv => drv.SwitchTo().Alert());

would then become

IAlert alert = wait.Until(drv => AlertIsPresent(drv));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top