Saturday 23 May 2015

Selenium WebDriver : Handling Javascript Alerts, Confirmations And Prompts

 

Alerts, Confirmation and prompts are very commonly used elements of any web page and you must know how to handle popups in selenium web driver. If you know Selenium IDE has many commands to handle alerts, confirmation and popups like assertAlert, assertConfirmation, storeAlert, verifyAlertPresent etc. firts of all let me show you all three different popups types to remove confusion from your mind then we will see how to handle them in selenium webdriver.

 Alert Popup

Generally alert message popup display with alert text and Ok button as shown In bellow given Image.

 

 

Confirmation Popup
Confirmation popup displays with confirmation text, Ok and Cancel button as shown In bellow given Image.

 


Prompt Popup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.

 

Selenium webdriver has Its own Alert Interface to handle all above different popups. Alert Interface has different methods like accept(), dismiss(), getText(), sendKeys(java.lang.String keysToSend) and we can use all these methods to perform different actions on popups.

 
 

  
package Testng_Pack;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
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://only-testing-blog.blogspot.in/2014/01/textbox.html");
 }

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

 @Test
 public void Text() throws InterruptedException {
  //Alert Pop up Handling.
  driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
  //To locate alert.
  Alert A1 = driver.switchTo().alert();
  //To read the text from alert popup.
  String Alert1 = A1.getText();
  System.out.println(Alert1);
  Thread.sleep(2000);
  //To accept/Click Ok on alert popup.
  A1.accept();
  
  //Confirmation Pop up Handling.
  driver.findElement(By.xpath("//button[@onclick='myFunction()']")).click();
  Alert A2 = driver.switchTo().alert();
  String Alert2 = A2.getText();
  System.out.println(Alert2);
  Thread.sleep(2000);
  //To click On cancel button of confirmation box.
  A2.dismiss();
  
  //Prompt Pop up Handling.
  driver.findElement(By.xpath("//button[contains(.,'Show Me Prompt')]")).click();
  Alert A3 = driver.switchTo().alert();
  String Alert3 = A3.getText();
  System.out.println(Alert3);
  //To type text In text box of prompt pop up.
  A3.sendKeys("This Is John");
  Thread.sleep(2000);
  A3.accept();  
 }
}
 

This way you can handle different kind of alerts very easily using Alert Interface of selenium webdriver.


How To Handle Unexpected Alerts In Selenium WebDriver

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.

 

Saturday 28 February 2015

Accessing Multiple Links in the Web Page

One of the common procedures in web testing is to test if all the links present within the page are working. This can be conveniently done using a combination of the Java for-each loop and the By.tagName("a") method. The WebDriver code below checks each link from the Mercury Tours homepage to determine those that are working and those that are still under construction. 

--------------------------------------------------------------------------------------------------------------------------------
 
package com.company;

import org.openqa.selenium.By;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class AllLinks {


    public static void main(String[] args) {
        String baseUrl = "http://newtours.demoaut.com/";
        WebDriver driver = new FirefoxDriver();
        String underConsTitle = "Under Construction: Mercury Tours";
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

        driver.get(baseUrl);
        List<WebElement> linkElements = driver.findElements(By.tagName("a"));
        String[] linkTexts = new String[linkElements.size()];
        int i = 0;

        //extract the link texts of each link element        for (WebElement e : linkElements)
        {
            linkTexts[i] = e.getText();
            i++;
        }

        //test each link        for (String t : linkTexts)
        {
            driver.findElement(By.linkText(t)).click();
            if (driver.getTitle().equals(underConsTitle))
            {
                System.out.println("\"" + t + "\""                        + " is under construction.");
            } else            {
                System.out.println("\"" + t + "\""                        + " is working.");
            }
            driver.navigate().back();
        }
        driver.quit();
    }
}

--------------------------------------------------------------------------------------------------------------------------------
 

Sunday 18 January 2015

How to works with Ajax controls using Selenium Webdriver

AJAX stands for Asynchronous JavaScript and AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page. In AJAX driven web applications, data is retrieved from server without refreshing the page.

When we perform any action on Ajax controls, using Wait commands will not work as the page is not actually refreshed here. Pausing the test execution using threads for a certain period of time is also not a good approach as web element might appear later or earlier than the stipulated period of time depending on the system’s responsiveness, load or other uncontrolled factors of the moment, leads to test failures.

The best approach would be to wait for the required element in a dynamic period and then continue the test execution as soon as the element is found/visible.

This can done achieved with WebDriverWait in combination with ExpectedCondition , the best way to wait for an element dynamically, checking for the condition every second and continuing to the next command in the script as soon as the condition is met.

There are many methods which are available to use with wait.until(ExpectedConditions.anyCondition); The below is the image for the number of methods which are available.
The below are the few which we use regularly when testing an application :-

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.presenceOfElementLocated(locator));

The above statement will check for the element presence on the DOM of a page. This does not necessarily mean that the element is visible.

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
 
The above syntax will for the element present in the DOM of a page is visible.
Some times we may also need to check if the element is invisible or not. To do this we need use the below :

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));

Some times you will get an exception as ""org.openqa.selenium.WebDriverException: Element is not clickable at point (611, 419). Other element would receive the click:'. The below one is used to wait for the element to be clickable.

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.elementToBeClickable(locator));


------------------------------------------------------------------------------------------------------------------
package com.pack.ajax;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class AjaxExample {
 
 private String URL = "http://demos.telerik.com/aspnet-ajax/
                                  ajax/examples/loadingpanel/explicitshowhide/defaultcs.aspx";
 
 WebDriver driver;
 WebDriverWait wait;
 
 @BeforeClass
 public void setUp() {
  driver=new FirefoxDriver();
  driver.manage().window().maximize();
  driver.navigate().to(URL);
 }
 
 @Test
 public void test_AjaxExample() {

  /*Wait for grid to appear*/
  By container = By.cssSelector(".demo-container");
  wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.presenceOfElementLocated(container));
  
  /*Get the text before performing an ajax call*/
  WebElement noDatesTextElement = driver.findElement(By.xpath("//div[@class='RadAjaxPanel']/span"));
  String textBeforeAjaxCall = noDatesTextElement.getText().trim();
  
  /*Click on the date*/
  driver.findElement(By.linkText("1")).click();
 
  /*Wait for loader to disappear */
  By loader = By.className("raDiv");
  wait.until(ExpectedConditions.invisibilityOfElementLocated(loader));
  
  /*Get the text after ajax call*/
  WebElement selectedDatesTextElement = driver.findElement(By.xpath("//div[@class='RadAjaxPanel']/span"));
  wait.until(ExpectedConditions.visibilityOf(selectedDatesTextElement));
  String textAfterAjaxCall = selectedDatesTextElement.getText().trim();
  
  /*Verify both texts before ajax call and after ajax call text.*/
  Assert.assertNotEquals(textBeforeAjaxCall, textAfterAjaxCall);
  
  String expectedTextAfterAjaxCall = "Thursday, January 01, 2015";
  
  /*Verify expected text with text updated after ajax call*/
  Assert.assertEquals(textAfterAjaxCall, expectedTextAfterAjaxCall);
 }

}
  
------------------------------------------------------------------------------------------------------------------

Select Language