Automation Using Selenium Webdriver
Showing posts with label How To Handle Unexpected Alerts In Selenium WebDriver. Show all posts
Showing posts with label How To Handle Unexpected Alerts In Selenium WebDriver. Show all posts

Friday 28 October 2016

How To Handle Unexpected Alerts In Selenium WebDriver

I have one example where alert Is displaying when loading software web page. So we can check for alert Inside try catch block after page load as shown In bellow given example. After loading page,
It will check for alert. If alert Is there on the page then It will dismiss It else It will go to catch block and print message as shown In bellow given example.

Run bellow given example In eclipse with testng and observe the result.



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class unexpected_alert {
 WebDriver driver;

 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();  
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://any website alert");
 }

 @AfterTest
 public void tearDown() throws Exception {
  driver.quit();
 }

 @Test
 public void Text() throws InterruptedException {
  //To handle unexpected alert on page load.
  try{
   driver.switchTo().alert().dismiss();
  }catch(Exception e){
   System.out.println("unexpected alert not present");
  }

  driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname");
  driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname");
  driver.findElement(By.xpath("//input[@type='submit']")).click();
 }
}

Above given webdriver code Is just for example. It Is just explaining the way of using try catch block to handle unexpected alert.
You can use such try catch block In that area where you are facing unexpected alerts very frequently.