org.openqa.selenium.NoAlertPresentException: no alert open
The code has to wait for alert. Below is the sample code
try { WebDriverWait wait = new WebDriverWait(driver, 2); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); System.out.println(alert.getText()); alert.accept(); Assert.assertTrue(alert.getText().contains("Thanks."));} catch (Exception e) { //exception handling}
This is a very bad approach to use try-catch
especially in selenium based test cases and their use should be limited:
Let's understand the real solution of this problem and why the given solution is incorrect because:
If we try to call
alert.getText()
afteralert.accept();
it would obvious that it going to throw error because we have already closed the alert.It is working fine because by using
try-catch
, it will going to handle the exception.The problem is that assertion is never checked here.
Code: The below code will terminate every time even before checking the assertion.
alert.accept(); Assert.assertTrue(alert.getText().contains("Thanks."));
Corrected Code: The alert.accept();
should be call after getting the text.
WebDriverWait wait = new WebDriverWait(driver, 2); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); Assert.assertTrue(alert.getText().contains("Thanks.")); alert.accept();