Wednesday 28 October 2015

Selenium Grid

 

Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). Selenium-Grid support distributed test execution. It dramatically accelerates the testing process across different browsers and platforms by giving us quick and accurate feedback and result.

Selenium Grid allows us to execute multiple instances of WebDriver tests in parallel which uses the same code base; hence the code need NOT be present on the system on which the test is executing. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid.

Selenium grid has two essential components Node and Hub:

Hub: As the name suggests this is the central point where the tests would be triggered .The hub can also be understood as a server. A Selenium Grid has only one Hub and it is launched on a single machine.

Node: Nodes are the Selenium instances that are attached to Hub which execute the tests. There can be more than one node in a grid which can be of any OS and can contain any of the Selenium supported browsers.

Architecture

Following diagram will give you the whole idea about how the Selenium Grid works.

clip_image002

Working with Grid

In order to work with the Grid, we need to follow certain protocols. This are the major steps involved in this process:

  • Configuring the Hub.
  • Configuring the Nodes.
  • Develop the Script and Prepare the XML File.
  • Test Execution.
  • Result Analysis.

Configuring Hub

Step 1:

Download the latest Selenium Server standalone JAR file from

http://docs.seleniumhq.org/download/.

clip_image004

Step 2:

Start the Hub by launching the Selenium Server using the following command. Now we will use the port '4444' to start the hub.

Note: Ensure that there are no other applications that are running on port no. 4444.

java -jar selenium-server-standalone-2.48.0.jar -port 4444 -role hub -nodeTimeout 1000

clip_image006

Step 3:

Now open the browser and navigate to the URL http//localhost:4444 from the Hub (The system where you have executed Step 2).

clip_image008

Step 4:

Now click on the 'console' link and click 'view config'. The configuration of the hub would be displayed as follows. As of now, we haven't got any nodes; hence we will not be able to see the details.

Configuring Node

Step 1:

Logon to the node (where you would like to execute the scripts) and place the 'selenium-server-standalone-2.48.2' in a folder. We need to point to the selenium-server-standalone JAR while launching the nodes.

Step 2 :

Launch FireFox Node using the following command.

java -jar D:\JAR\selenium-server-standalone-2.42.2.jar -role node -hub http://10.30.217.157:4444/grid/register -browser browserName=firefox -port 5555

Where,

D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)

http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub

browserName = firefox (Parameter to specify the Browser name on Nodes)

5555 = Port on which Firefox Node would be up and running.

clip_image010

Step 3:

After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the node attached to it.

clip_image012

Step 4:

Now let us launch the Internet Explorer Node. For launching the IE Node, we need to have the Internet Explorer driver downloaded on the node machine.

Step 5:

To download the Internet Explorer driver, navigate to http://docs.seleniumhq.org/download/ and download the appropriate file based on the architecture of your OS. After you have downloaded, unzip the exe file and place it in a folder which has to be referred while launching IE nodes.

clip_image014

Step 6:

Launch IE with following command.

C:\>java -Dwebdriver.ie.driver=D:\IEDriverServer.exe -jar D:\JAR\selenium-server-standalone-2.48.2.jar -role webdriver -hub http://10.30.217.157:4444/grid/register -browser browserName=ie,platform=WINDOWS -port 5558

Where,

D:\IEDriverServer.exe = The location of the downloaded the IE Driver(on the Node Machine)

D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)

http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub

browserName = ie (Parameter to specify the Browser name on Nodes)

5558 = Port on which IE Node would be up and running.

clip_image016

Step 7:

After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the IE node attached to it.

Step 8:

Let us now launch the Chrome Node. For launching the Chrome Node, we need to have the Chrome driver downloaded on the node machine.

Step 9:

To download the Chrome Driver, navigate to http://docs.seleniumhq.org/download/ and then navigate to Third Party Browser Drivers area and click on the version number '2.20' as shown below.

clip_image018

Step 10:

Launch Chrome using the following command.

       
   

C:\>java -Dwebdriver.chrome.driver=D:\chromedriver.exe -jar D:\JAR\selenium-server-standalone-2.48.2.jar -role webdriver -hub http://10.30.217.157:4444/grid/register -browser browserName=chrome,platform=WINDOWS -port 5557

 
 

Where,

D:\chromedriver.exe = The location of the downloaded the chrome Driver(on the Node Machine)

D:\JAR\selenium-server-standalone-2.48.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)

http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub

browserName = chrome (Parameter to specify the Browser name on Nodes)

5557 = Port on which chrome Node would be up and running.

clip_image020

Now the whole Environment is setup for working with Selenium Grid.

Developing script and Preparing XML file

We can develop a test using TestNG. We can launch each one of those browsers using remote WebDriver. It can pass on their capabilities to the driver so that the driver has all the information to execute on Nodes.

The Browser Parameter would be passed from the "XML" file. The contents of the XML file can create tests and put them in a suite and mention parallel="tests" so that all the tests could be executed in parallel.

Result Analysis

Step 1:

Upon completing the execution, we can analyze the result like any other execution. The result summary is printed in the console as shown in the following snapshot.

clip_image022

Step 2:

Navigate to the 'Results of Running Suite' Tab and TestNG would display the result summary as shown below.

clip_image024

Step 3:

Upon generating the HTML, we will be able to see the test results in HTML format.

clip_image026

Conclusion

This tutorial has taught you how to use Selenium to create your own tests.

Selenium is an open-source tool that is used for test automation. It is licensed under Apache License 2.0. Selenium is a suite of tools that helps in automating only web applications.

Now you are a partial professional in Selenium and you can take your expertise in selenium to next level by practicing it in your projects. Thank you..!!

 

References

The following resources contain additional information on Selenium. Please use them to get more in-depth knowledge on this topic.

Useful Links on Selenium

Wikipedia- Wikipedia reference for Selenium.

Selenium Reference - This User Guide is provided Selenium Contributing team.

Books for Reference

1. Selenium 2 Testing Tools.

2. A Practitioner's Guide to Test Automation using SELENIUM

3. Selenium WebDriver in C#.Net : Learn with Examples

TEST DESIGN TECHNIQUES

 

By Test Designing we mean to make a plan for implementing tests and techniques is the method of implementing that test plans. So, Test Design is nothing but to create a set of inputs to get the set of expected outputs. Various elements involved in designing a test. Let’s understand some of the important elements which help us in designing a framework. We will learn following topics in this article:

  • Page Object Model (POM).
  • Architecture of POM.
  • POM Example
  • Data driven using Excel.
  • Parameterization.
  • Log4j Logging
  • Exception handling.
  • Screen Capturing.

Page Object Model

Selenium interacts with the web-elements with the help of IDs, Class, names, XPaths etc. For accessing web elements every time we need to get the element’s properties and write into our code to access it. To make coding feasible we use Object Repository (OR). Object Repository is a centralized location where we can store objects information, it acts as interface between Test script and application in order to identify the objects during the execution. Selenium has no inbuilt object repository (OR) like QTP. Hence we need to create an OR which could be available when needed and also which is maintainable.

Page Object Model (POM) is a popular design pattern to create an object repository in selenium. Each of the web element properties are stored in a single class file.

Architecture of POM

Objects are created for each one of the pages and methods are developed exclusively to access to those objects. Let us use http://calculator.net for understanding the same. There are various calculators associated with it and each one of those objects in a particular page is created in a separate class file as static methods and they all are accessed through the 'tests' class file in which a static method would be accessing the objects.

clip_image002

Example

Let us understand it by implementing POM .

Step 1:

Create a simple class (page_objects_pcent_calc.java) file within a package and create methods for each one of those objects identifiers as shown below.

import org.openqa.selenium.*;

public class page_objects_pcent_calc {

private static WebElement element = null;

// Math Calc Link

public static WebElement lnk_math_calc(WebDriver driver)

{

element =driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a"));

return element;

}

// Percentage Calc Link

public static WebElement lnk_percent_calc(WebDriver driver)

{

element =

driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"));

return element;

}

// Number 1 Text Box

public static WebElement txt_num_1(WebDriver driver)

{

element = driver.findElement(By.id("cpar1"));

return element;

}

// Number 2 Text Box

public static WebElement txt_num_2(WebDriver driver)

{

element = driver.findElement(By.id("cpar2"));

return element;

}

// Calculate Button

public static WebElement btn_calc(WebDriver driver)

{

element =

driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/tr[2]/td/input[2]"));

return element;

}

// Result

public static WebElement web_result(WebDriver driver)

{

element = driver.findElement(By.xpath(".//*[@id='content']/p[2]/font/b"));

return element;

}

}

Step 2:

Create a class with main and import the package and create methods for each one of those objects identifiers as shown below.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("http://www.calculator.net");

// Maximize the browser

driver.manage().window().maximize();

// Use page Object library now

page_objects_pcent_calc.lnk_math_calc(driver).click();

page_objects_pcent_calc.lnk_percent_calc(driver).click();

page_objects_pcent_calc.txt_num_1(driver).clear();

page_objects_pcent_calc.txt_num_1(driver).sendKeys("10");

page_objects_pcent_calc.txt_num_2(driver).clear();

page_objects_pcent_calc.txt_num_2(driver).sendKeys("50");

page_objects_pcent_calc.btn_calc(driver).click();

String result = page_objects_pcent_calc.web_result(driver).getText();

if(result.equals("5"))

{

System.out.println(" The Result is Pass");

}

else

{

System.out.println(" The Result is Fail");

}

driver.close();

}

}

Output

The test is executed and the result is printed in the console. Given below is the snapshot of the same.

clip_image004

Data Driven Using Excel

Parameterizing is the important aspect of any programming language. While designing a test in selenium, we invite parameterizing for our tests. We will use Apache POI – Excel JAR for the same. This JAR helps us to read and write excel.

Step 1:

Navigate to the URL - http://poi.apache.org/download.html and download Zip.

clip_image006

Step 2:

Unzip the content.

clip_image008

Step 3:

Now create a project and add all the ‘External JARs’ .

clip_image010

Step 4:

Also add all ‘External JARs’ under the ‘ooxml-lib’ and ‘lib’ folder.

clip_image012

Step 5:

The Package Explorer is displayed as shown below. Apart from that, add 'WebDriver' related JAR's.

clip_image014

Parameterization

For demonstration, we will parameterize the Excel file by reading and writing excel.

Step 1:

We will parameterize all the inputs required for using Excel. The designed Excel is shown below.

clip_image016

Step 2:

Execute all functions for all the specified parameters.

Step 3:

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelRead {

public void readExcel(String filePath,String fileName,String sheetName) throws IOException{

//Create a object of File class to open xlsx file

File file = new File(filePath+"\\"+fileName);

//Create an object of FileInputStream class to read excel file

FileInputStream inputStream = new FileInputStream(file);

Workbook Workbook = null;

//Find the file extension by spliting file name in substring and getting only extension name

String fileExtensionName = fileName.substring(fileName.indexOf("."));

//Check condition if the file is xlsx file

if(fileExtensionName.equals(".xlsx")){

//If it is xlsx file then create object of XSSFWorkbook class

Workbook = new XSSFWorkbook(inputStream);

}

Let us create generic methods to access the Excel file using the imported JARs. These methods help us get a particular cell data or to set a particular cell data, etc.

//Check condition if the file is xls file

else if(fileExtensionName.equals(".xls")){

//If it is xls file then create object of XSSFWorkbook class

Workbook = new HSSFWorkbook(inputStream);

}

//Read sheet inside the workbook by its name

Sheet guru99Sheet = Workbook.getSheet(sheetName);

//Find number of rows in excel file

int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();

//Create a loop over all the rows of excel file to read it

for (int i = 0; i < rowCount+1; i++) {

Row row = guru99Sheet.getRow(i);

//Create a loop to print cell values in a row

for (int j = 0; j < row.getLastCellNum(); j++) {

//Print excel data in console

System.out.print(row.getCell(j).getStringCellValue()+"|| ");

}

System.out.println();

}

}

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

//Create a object of ReadGuru99ExcelFile class

ExcelRead objExcelFile = new ExcelRead();

//Prepare the path of excel file

//String filePath = System.getProperty("user.dir")+"\\src\\excelExportAndFileIO";

//Call read file method of the class to read data

objExcelFile.readExcel("E:\\","Book1.xlsx","Sheet1");

}

}

Output

clip_image018

Step 4:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class writeExcel {

public void writingExcel(String filePath,String fileName,String sheetName,String[] dataToWrite) throws IOException{

//Create a object of File class to open xlsx file

File file = new File(filePath+"\\"+fileName);

//Create an object of FileInputStream class to read excel file

FileInputStream inputStream = new FileInputStream(file);

Workbook Workbook = null;

//Find the file extension by spliting file name in substing and getting only extension name

String fileExtensionName = fileName.substring(fileName.indexOf("."));

//Check condition if the file is xlsx file

if(fileExtensionName.equals(".xlsx")){

//If it is xlsx file then create object of XSSFWorkbook class

Workbook = new XSSFWorkbook(inputStream);

}

Let us learn how to read an excel file.

//Check condition if the file is xls file

else if(fileExtensionName.equals(".xls")){

//If it is xls file then create object of XSSFWorkbook class

Workbook = new HSSFWorkbook(inputStream);

}

//Read excel sheet by sheet name

Sheet sheet = Workbook.getSheet(sheetName);

//Get the current count of rows in excel file

int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

//Get the first row from the sheet

Row row = sheet.getRow(0);

//Create a new row and append it at last of sheet

Row newRow = sheet.createRow(rowCount+1);

//Create a loop over the cell of newly created Row

for(int j = 0; j < row.getLastCellNum(); j++){

//Fill data in row

Cell cell = newRow.createCell(j);

cell.setCellValue(dataToWrite[j]);

}

//Close input stream

inputStream.close();

//Create an object of FileOutputStream class to create write data in excel file

FileOutputStream outputStream = new FileOutputStream(file);

//write data in the excel file

Workbook.write(outputStream);

//close output stream

outputStream.close();

}

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

//Create an array with the data in the same order in which you expect to be filled in excel file

String[] valueToWrite = {"Mr. x","Goa"};

//Create an object of current class

writeExcel objExcelFile = new writeExcel();

//Write the file using file name , sheet name and the data to be filled

objExcelFile.writingExcel("E:\\","Book1.xlsx","Sheet1",valueToWrite);

}

}

Output

clip_image020

Log4j Logging

Log4j is a fast, flexible and reliable logging framework. Log4j is an audit logging framework that gives information about what has happened during execution. It offers the following advantages:

· Enables us to understand the application run.

· Log output can be saved that can be analyzed later.

· Helps in debugging, in case of test automation failures.

· Can also be used for auditing purposes to look at the application's health.

Components

1. Instance of Logger class.

2. Log level methods used for logging the message as one of the following:

a. Error

b. Warn

c. Info

d. Debug

e. Log

Example

Step 1:

Download Log4j JARs from https://logging.apache.org/log4j/1.2/download.html

clip_image022

Step 2:

Make a new project and add ‘External JARs’ from the extracted ‘apache-log4j-1.2.17’ of zip file downloaded from the previous step.

clip_image024

Step 3:

Also add all the Selenium support JARs.

Step 4:

Add a new XML file using we can specify the Log4j properties by right-clicking on project Folder >> new >> File

clip_image026

Name the file as ‘Log4j.properties’.

Step 5:

The final folder structure is shown below.

clip_image028

Step 6:

Now add the properties of Log4j which would be picked up during execution.

clip_image030

Step 7:

Create a main class and copy the following code.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.apache.log4j.Logger;

public class LoggingDemo {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

Logger log = Logger.getLogger("devpinoyLogger");

driver.get("<a href="http://healthunify.com/bmicalculator/">http://healthunify.com/bmicalculator/</a>"); log.debug("opening webiste");

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

log.debug("entring weight");

driver.findElement(By.name("wg")).sendKeys("87");

log.debug("selecting kilograms");

driver.findElement(By.name("opt1")).sendKeys("kilograms");

log.debug("selecting height in feet");

driver.findElement(By.name("opt2")).sendKeys("5");

log.debug("selecting height in inchs");

driver.findElement(By.name("opt3")).sendKeys("10");

log.debug("Clicking on calculate");

driver.findElement(By.name("cc")).click();

log.debug("Getting SIUnit value");

String SIUnit = driver.findElement(By.name("si")).getAttribute("value");

log.debug("Getting USUnit value");

String USUnit = driver.findElement(By.name("us")).getAttribute("value");

log.debug("Getting UKUnit value");

String UKUnit = driver.findElement(By.name("uk")).getAttribute("value");

log.debug("Getting overall description");

String note = driver.findElement(By.name("desc")).getAttribute("value");

System.out.println("SIUnit = " + SIUnit);

System.out.println("USUnit = " + USUnit);

System.out.println("UKUnit = " + UKUnit);

System.out.println("note = " + note);

driver.quit();

}

}

In the above code, we visit http://healthunify.com/bmicalculator/and verify BMI calculator. The weight entered is 87KG and the height is 5 Feet 10 inches. The script checks output in SE, US and UK units.

Using Logger.getLogger("devpinoyLogger") we create system level logs

Using log.debug method we store data into Manual.log

Step 8:

Run the script. Open the location of Manual and Selenium logs to check logging data.

Exception Handling

When we are developing tests, we should ensure that the scripts can continue their execution even if the test fails. An unexpected exception would be thrown if the worst case scenarios are not handled properly.

If an exception occurs due to an element not found or if the expected result doesn't match with actuals, we should catch that exception and end the test in a logical way rather than terminating the script abruptly.

Syntax

The actual code should be placed in the try block and the action after exception should be placed in the catch block. Note that the 'finally' block executes regardless of whether the script had thrown an exception or NOT.

try

{

// Perform Action

}

catch(ExceptionType1 exp1)

{

// Catch block 1

}

catch(ExceptionType2 exp2)

{

// Catch block 2

}

catch(ExceptionType3 exp3)

{

// Catch block 3

}

finally

{

// The finally block always executes.

}

Screen Capturing

This functionality helps to grab screenshots at runtime when required, in particularly when a failure happens. With the help of screenshots and log messages, we will be able to analyze the results better.

Screenshots are configured differently for local executions and Selenium Grid (remote) executions. Let us take a look at each one of them with an example.

Localhost Execution

import java.io.File;

import java.io.IOException;

import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

public class webdriverdemo

{

public static void main(String[] args) throws IOException

{

WebDriver driver = new FirefoxDriver();

In the following example, we will take a screenshot after calculating the percentage. Ensure that you give a valid path to save the screenshot.

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("http://www.calculator.net/");

// Maximize the browser

driver.manage().window().maximize();

// Click on Math Calculators

driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();

// Click on Percent Calculators

driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();

// Enter value 10 in the first number of the percent Calculator

driver.findElement(By.id("cpar1")).sendKeys("10");

// Enter value 50 in the second number of the percent Calculator

driver.findElement(By.id("cpar2")).sendKeys("50");

// Click Calculate Button

driver.findElement(By.xpath(".//*[@id='content']/table

/tbody/tr/td[2]/input")).click();

// Get the Result Text based on its xpath

String result =

driver.findElement(By.xpath(".//*[@id='content']/p[2]

/span/font/b")).getText();

File screenshot =

((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(screenshot, new

File("D:\\screenshots\\screenshots1.jpg"));

// Print a Log In message to the screen

System.out.println(" The Result is " + result);

// Close the Browser.

driver.close();

}

}

As a output the image file containing the desired screen shot will be generated.

What’s next?

In next article we will learn Selenium Grid.

ACCESSING WEB ELEMENTS

 

Selenium WebDriver is widely used tools in selenium tool set. To use Selenium WebDriver it is important to learn how it interacts with your application’s web elements. In this article, we will learn how to access your application’s web elements using Selenium WebDriver.

Below is the list of actions which is being used during your application’s test:

  • Accessing Text-Box.
  • Accessing Radio Buttons.
  • Accessing check Box.
  • Drop Down box Selection.
  • Synchronization.
  • Drag & Drop.
  • Keyboard Actions.
  • Mouse Actions.
  • Multi Selection.
  • Find all Links.

Accessing Text-Box

During your web application test the first thing you face is the text box for entering credentials for your application. In this section we will understand how to interact and access text box. We can put values into the text box using SendKey(). Similarly, we can retrieve the values using getattribute(“value”) command.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

// Launch website

driver.navigate().to("www.facebook.com");

// Maximize the browser

driver.manage().window().maximize();

// Enter value 10 in the first number of the percent Calculator

driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("John@gmail.com");

Thread.sleep(5000);

// Get the text box from the application

String result = driver.findElement(By.xpath(".//*[@id='email']")).getAttribute("value");

// Print a Log In message to the screen

System.out.println(" The Result is " + result);

// Close the Browser

driver.close();

}

}

The output of this code is like this:

clip_image002

Accessing Radio Buttons

In this section, we will learn how to deal with radio buttons in your application. We just have to use click() to select and unselect radio buttons in your application.

We will understand accessing radio button using https://www.utexas.edu/learn/forms/radio.html. We can also check if a radio button is selected or enabled.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("https://www.utexas.edu/learn/forms/radio.html");

// Maximize the browser

driver.manage().window().maximize();

// Click on Radio Button

driver.findElement(By.xpath(".//*[@id='mr']")).click();

System.out.println("The Output of the IsSelected " +

driver.findElement(By.xpath(".//*[@id='mr']")).isSelected());

System.out.println("The Output of the IsEnabled " +

driver.findElement(By.xpath(".//*[@id='mr']")).isEnabled());

System.out.println("The Output of the IsDisplayed " +

driver.findElement(By.xpath(".//*[@id='mr']")).isDisplayed());

// Close the Browser.

driver.close();

}

}

The result of this code is:

clip_image004

Accessing check Box

In this section, we will learn how to run your test when you come across with check box during testing your application. We can select a check box using the click() and uncheck using the same click() method.

Let us understand how to interact with a dropdown box using //www.utexas.edu/learn/forms/checkboxes.html.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("https://www.utexas.edu/learn/forms/checkboxes.html");

// Maximize the browser

driver.manage().window().maximize();

// Click on check box

System.out.println("The Output of the IsSelected " +

driver.findElement(By.xpath(".//*[@id='graphics']")).isSelected());

driver.findElement(By.xpath(".//*[@id='graphics']")).click();

System.out.println("The Output of the IsEnabled " +

driver.findElement(By.xpath(".//*[@id='graphics']")).isEnabled());

System.out.println("The Output of the IsDisplayed " +

driver.findElement(By.xpath(".//*[@id='graphics']")).isDisplayed());

// Close the Browser.

driver.close();

}

}

Upon execution, the check box is unchecked after the click command (as it was checked by default) and the output of the commands are displayed in the console.

clip_image006

Drop down box Selection

In this section, we will understand how to interact with Dropdown Boxes. We can select an option using selectByVisibleText() or selectByIndex() or selectByValue() methods.

Let us understand how to interact with a dropdown box using

http://www.calculator.net/interest-calculator.html.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("http://www.calculator.net/interest-calculator.html");

// Maximize the browser

driver.manage().window().maximize();

// Selecting an item from Drop Down list Box

Select dropdown = new Select(driver.findElement(By.id("ccompound")));

dropdown.selectByVisibleText("continuously");

// you can also use dropdown.selectByIndex(1) to

// select second element as index starts with 0.

// You can also use dropdown.selectByValue("annually");

System.out.println("The Output of the IsSelected " +

driver.findElement(By.id("ccompound")).isSelected());

System.out.println("The Output of the IsEnabled " +

driver.findElement(By.id("ccompound")).isEnabled());

System.out.println("The Output of the IsDisplayed " +

driver.findElement(By.id("ccompound")).isDisplayed());

// Close the Browser.

driver.close();

}

}

Output

Upon execution, the dropdown is set with the specified value and the output of the commands are displayed in the console.

clip_image008

Synchronization

To synchronize between script execution and application, we need to wait for sometime after performing some actions. Let us look how to implement it.

Thread.Sleep

Thread.Sleep is a static wait and it is not a good way to use in scripts, as it is sleep without condition.

Thread.Sleep(1000); //Will wait for 1 second.

Explicit Waits

An 'explicit wait' waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on an object once it is visible.

 
 

WebDriver driver = new FirefoxDriver();

driver.get("Enter an URL"S);

WebElement DynamicElement = (new WebDriverWait(driver,10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

Implicit Wait

Implicit wait is used in cases where the WebDriver cannot locate an object immediately because of its unavailability. The WebDriver will wait for a specified implicit wait time and it will not try to find the element again during the specified time period.

Once the specified time limit is crossed, the WebDriver will try to search the element once again for one last time. Upon success, it proceeds with the execution; upon failure, it throws an exception.

It is a kind of global wait which means the wait is applicable for the entire driver. Hence, hardcoding this wait for longer time periods will hamper the execution time.

 
 

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get("Enter an URL");

WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));

Drag & Drop

As a tester, you might be in a situation to perform a 'Drag & drop' operation. We will perform a drag and drop operation by picking up a tree grid that is available for us on http://jqueryui.com/droppable/.

We will drop this small box into the big one by dragging it.

clip_image010

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.interactions.Action;

import org.openqa.selenium.interactions.Actions;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("http://jqueryui.com/droppable/");

// Maximize the browser

driver.manage().window().maximize();

WebElement From =

driver.findElement(By.xpath(".//*[@id='draggable']"));

WebElement To =

driver.findElement(By.xpath(".//*[@id='droppable']"));

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(From).moveToElement(To).release(To).build();

dragAndDrop.perform();

// Close the Browser.

driver.close();

}

}

Output

clip_image012

Keyboard Actions

For performing keyboard actions following methods are used:

· sendKeys() - Sends keys to the keyboard representation in the browser. Keys are recognized both as part of sequences of characters, or individually.

· pressKey() – Used to press keys on the keyboard that is NOT text. The keys such as function keys "F1", "F2", "Tab", "Control", etc. If key is a sequence of characters, different driver implementations may choose to throw an exception or to read only the first character in the sequence.

· releaseKey() - Release a key on the keyboard after executing the keypress event. It usually holds good for non-text characters.

Syntax

 
 

void sendKeys(java.lang.CharSequence keysToSend);

void pressKey(java.lang.CharSequence keyToPress);

void releaseKey(java.lang.CharSequence keyToRelease);

Mouse Actions

For performing mouse actions following methods are used:

· Click() –To performs a Click. We can also perform a click based on coordinates.

· contextClick() – To Performs a context click/right-click on an element or based on the coordinates.

· doubleClick() – To performs a double-click on the webelement or based on the coordinates. If left empty, it performs double-click on the current location.

· mouseDown() – To performs a mouse-down action on an element or based on coordinates.

· mouseMove()- To performs a mouse-move action on an element or based on coordinates.

· mouseUp() – To releases the mouse usually followed by mouse-down and acts based on coordinates.

Syntax

 
 

void doubleClick(WebElement onElement);

void mouseDown(WebElement onElement);

void mouseUp(WebElement onElement);

void mouseMove(WebElement toElement);

void mouseMove(WebElement toElement, long xOffset, long yOffset);

Find All Links

Testers might be in a situation to find all the links on a website. We can easily do so by finding all elements with the Tag Name "a", as we know that for any link reference in HTML, we need to use "a" (anchor) tag.

For the demonstration we will grab all the links exists on the login page of www.facebook.com.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("www.facebook.com");

// Maximize the browser

driver.manage().window().maximize();

java.util.List<WebElement> links =driver.findElements(By.tagName("a"));

System.out.println("Number of Links in the Page is " +links.size());

for (int i = 1; i<=links.size(); i=i+1)

{

System.out.println("Name of Link# " + i + "-" + links.get(i).getText());

}

}

}

Output

clip_image014

Generation Xpaths

XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate in XML documents. XPath contains a library of standard functions. Now, there could be a situation when we face problem to grab the Xpaths. In that case we can generate xpath by our own by analysing the XML code.

Below table will help you out to make your own xpath from XML script.

Expression

Description

nodename

To select all nodes with the name “nodename”.

/

To select from the root node.

//

Selects node in the document from the current node that matches the selection no matter where they are.

.

Selects the current node.

..

Selects parent of the current node.

@

Select the attributes.

Example

Let’s create a xpath for firstname field of facebook login form:

clip_image016

Step 1: Select first name

//input[@id='firstname] OR //input[@name=firstname]

In this case no need of xpath locator because we can use By.id, By.name,By.cssSelector.

By.id("firstname") | By.name("firstname") | By.cssSelector("[id=firstname]")

Step 2: Selecting first name input using First Name label

//label[text()='First Name:']/parent::td/following-sibling::td/div/input

OR

//label[text()='First Name:']/../../td/div/input

What’s next?

In next article we will learn different test design techniques that simplifies your code and also make it more understandable and dynamic.

LOCATORS

 

Locators tells Selenium IDE on which web elements (Text Box, Buttons, Check Boxes etc) we need to work on. Locating web elements in Selenium WebDriver is done with the help of 2 methods findElement() and findElements() resides in WebElement class. Both the methods seems similar but there is difference between them.

Below I have mentioned the basic difference between both the methods:

findElement()

findElements()

Find the first element within the current page using the given "locating mechanism".

Find all elements within the current page using the given "locating mechanism".

Returns a single WebElement.

Returns List of WebElements.

Syntax: WebElement findElement(By locator)

Syntax: java.util.List<WebElement> findElements(By locator)

The following table lists all the Java syntax for locating elements in Selenium WebDriver.

Method

Syntax

Description

By ID

driver.findElement(By.id(<element ID>))

Locates an element using the ID attribute.

By name

driver.findElement(By.name(<element name>))

Locates an element using the Name attribute.

By class name

driver.findElement(By.className(<element class>))

Locates an element using the Class attribute.

By tag name

driver.findElement(By.tagName(<htmltagname>))

Locates an element using HTML tag names.

By link text

driver.findElement(By.linkText(<linktext>))

Locates a link using link text.

By partial link text

driver.findElement(By.partialLinkText(<linktext>))

Locates a link using the link's partial text.

By CSS

driver.findElement(By.cssSelector(<css selector>))

Locates an element using the CSS selector.

By XPath

driver.findElement(By.xpath(<xpath>))

Locates an element using XPath.

How to use Locators?

Now let us understand the practical usage of each of the locator methods with the help of http://www.facebook.com.

Locating By ID

This is the most common way of locating elements since ID's are supposed to be unique for each element.

Navigate to www.facebook.com and inspect the “Email or Phone” Textbox using Firebug add-on which we have already installed. Here an object is accessed with the help of IDs. In this case, it is the ID of the text box. Values are entered into the text box using the sendkeys() with the help of ID(email).

clip_image002

driver.findElement(By.id(“email”)).sendKeys(“abc@xyz.com”);

driver.findElement(By.id("cdensity")).sendKeys("10");

driver.findElement(By.id("cdensity")).sendKeys("10");

driver.findElement(By.id("cdensity")).sendKeys("10");

driver.findElement(By.id("cdensity")).sendKeys("10");

By Class name

Here an object is accessed with the help of Class Names. In this case, it is the Class name of the WebElement is “email”. The Value can be accessed with the help of the findElements().

clip_image004

 
 

List<WebElement> byclass = driver.findElements(By.className("email"));

By Tag Name

The DOM Tag Name of an element can be used to locate that particular element in the WebDriver. It is very easy to handle tables with the help of this method. Take a look at the following code.

WebElement table = driver.findElement(By.id("email"));

List<WebElement> row = table.findElements(By.tagName("tr"));

int rowcount = row.size();

By CSS

The CSS is used as a method to identify the web object, however NOT all browsers support CSS identification.

WebElement loginButton = driver.findElement(By.cssSelector("input.login"));

By XPath

XPath stands for XML path language. It is a query language for selecting nodes from an XML document. XPath is based on the tree representation of XML documents and provides the ability to navigate around the tree by selecting nodes using a variety of criteria.

clip_image006

driver.findElement(By.xpath(".//*[@id='email']")).sendkeys("abc@xyz.com");

What’s next?

In next article we will learn how to access different web elements and use them to make your test run.