Some times when we browsing software web
application, Display some unexpected alerts due to some error or some other
reasons. This kind of alerts not display every time but they are displaying only
some time. If you have created webdriver test case for such page and not handled
this kind of alerts In your code then your script will
fail Immediately If such unexpected alert pop up displayed.
Now unexpected alert appears only some times so we can not write direct code to
accept or dismiss that alert. In this kind of situation, we have to handle them
specially.
To handle this kind of unexpected alerts, You
must at least aware about on which action such unexpected alert Is generated.
Sometimes, They are generated during page load and sometime they are generated
when you perform some action. So first of all we have to note down the action
where such unexpected alert Is generated and then we can check for alert after
performing that action. We need to use try catch block for checking such
unexpected alters because If we will use direct code(without try catch) to
accept or dismiss alert and If alert not appears then our test case will fail.
try catch can handle both situations.
I have one example where alert Is displaying
when loading 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.
package com.company;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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;
import java.util.concurrent.TimeUnit;
public class HandleunexpectedAlert {
WebDriver driver;
@Before public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}
@After 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.
No comments:
Post a Comment