SUBSCRIBE HERE TO GET POST UPDATES VIA EMAIL :

Delivered by FeedBurner

WebDriver how to wait for alert in selenium 2

As we have seen in my previous posts, we can use textToBePresentInElementLocated(By, String) WebDriver condition to wait for text present on page and we can use elementToBeClickable(By locator) to wait for element clickable/present on page. If you read both those posts, We had used explicit waits in both the cases and both are canned expected conditions of webdriver so we can use them directly in our test case without any modifications.

Sometimes you will face wait for alert scenario where you have to wait for alert before performing any action on your software application web page. If you know, we can use "waitForAlert" command in selenium IDE to handle alerts. In WebDriver/Selenium 2, You can use WebDriver's built in canned condition alertIsPresent() with wait command as bellow.

WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());

Look in to above syntax. 1st syntax described how much time it has to wait and 2nd syntax describes the waiting condition. Here we have used alertIsPresent() condition so it will wait for the alert on page. Let me give you full practical example to describe scenario perfectly.

Copy paste bellow given test case in your eclipse with JUnit and then run it. You can View how to configure eclipse with JUnit if you have no idea.

package junitreportpackage;

import java.util.concurrent.TimeUnit;

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.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


public class Mytest1 {
 WebDriver driver = new FirefoxDriver();
 
 @Before
 public void beforetest() {
  driver.manage().window().maximize();
  driver.get("http://only-testing-blog.blogspot.in/2014/01/new-testing.html");
 }
 
 @After
 public void aftertest() {
  driver.quit();
  
 }
 
 @Test
 public void test () 
  {  
  driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
  WebDriverWait wait = new WebDriverWait(driver, 15);
  wait.until(ExpectedConditions.alertIsPresent());
  String alrt = driver.switchTo().alert().getText();
  System.out.print(alrt);
  }
 
 
 
 }

Above example will wait for the alert on page and as soon as alert appears on page, it will store alert text in variable 'alrt' and then will print to it in console.

No comments:

Post a Comment