Reputation: 45
I need my test to fail if there's an error popup on the screen after performing Print operation.
Currently, this code is working:
[TestMethod]
[Description("Should Print")]
public void PrintDetails()
{
mainPage.PrintDetails(driver);
Thread.Sleep(300);
Wait.WaitForNoErrorMsg(driver);
}
--
public static void WaitForNoErrorMsg(IWebDriver driver)
{
string errorMsg = "//div[@class='errorMessage']";
try
{
WaitForElementNotVisible(driver, errorMsg, 3);
}
catch (Exception)
{
throw;
}
}
--
public static void WaitForElementNotVisible(IWebDriver driver, string locator, int seconds)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.XPath(locator)));
}
I feel that's not an optimal way and it could be done better using ExpectedException. Am I right? Could you provide an example, please?
Upvotes: 2
Views: 201
Reputation: 5407
You can easily do this by making the following changes:
[TestMethod]
[Description("Should Print")]
[ExpectedException(typeof(ApplicationException))]
public void PrintDetails()
And:
public static void WaitForNoErrorMsg(IWebDriver driver)
{
string errorMsg = "//div[@class='errorMessage']";
try
{
WaitForElementNotVisible(driver, errorMsg, 3);
}
catch (Exception)
{
throw new ApplicationException();
}
}
What this will do is your test will expect an exception to be thrown and will only pass when the expected exception is thrown.
I wouldn't do this. Instead I would create two tests, one which tests the correct path and a second test that checks a bad scenario.
In both tests I would also skip on using exceptions altogether as they aren't needed and you can make things simpler by not using them.
I would change WaitForNoErrorMsg
to VerifyNoErrorMsg
and have it return a boolean:
public static bool WaitForNoErrorMsg(IWebDriver driver)
{
string errorMsg = "//div[@class='errorMessage']";
try
{
WaitForElementNotVisible(driver, errorMsg, 3);
}
catch (Exception)
{
return false;
}
return true;
}
And have your tests like this:
[TestMethod]
[Description("Should Print")]
public void PrintDetailsSuccess()
{
mainPage.PrintDetails(driver);
Thread.Sleep(300);
bool errorMessagePresent = WaitForNoErrorMsg(driver);
Assert.IsFalse(errorMessagePresent);
}
Upvotes: 1