Showing posts with label Selenium Webdriver. Show all posts
Showing posts with label Selenium Webdriver. Show all posts

Saturday, July 16, 2016

Data Driven Approach - Using HashMap/Dictionary for Selenium automation

In this article, we will discuss how to create data dictionary or hash map in Java for data driven tests and read the data from the excel/csv file similar to dictionary object. Please go through below code example to read data from the external source using hashmap/dictionary or data driven approach. Please suggest or comment for better approach for data driven testing in java for Selenium.


package testingtest;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

class testclass {

 static String[][] getexceldatainArray;
 static HashMap<String, String> dictionary;

 public static void main(String[] args) throws IOException, BiffException {
  // Create an array based on data in excel file
  excelarrayclass tc = new excelarrayclass();
  getexceldatainArray = tc.CreateArrayfromExcel("D:\\Testing.xls",
    "testing");
  for (int i = 0; i < getexceldatainArray.length; i++) {
   dictionary = DataDictionaryFromArray(getexceldatainArray, i);
   // the keys will be value in the header column
   String username = dictionary.get("UserName");
   /*
    * Perform the required operation using the dictionary values
    */
   System.out.println("UserName " + username);
  }
 }

 public String[][] CreateArrayfromExcel(String WorkbookName, String SheetName)
   throws BiffException, IOException {
  String[][] arrTestDta;

  Workbook workbk = Workbook.getWorkbook(new File(WorkbookName));
  Sheet wrkSheet = workbk.getSheet(SheetName);
  arrTestDta = new String[wrkSheet.getRows()][wrkSheet.getColumns()];

  // Loop to get data from excel file into an array

  for (int i = 0; i < wrkSheet.getRows(); i++) {
   for (int j = 0; j < wrkSheet.getColumns(); j++) {
    Cell cell = wrkSheet.getCell(j, i);
    if (cell.getContents() != null) {
     arrTestDta[i][j] = cell.getContents();
    }
   }
  }
  return arrTestDta;
 }

 public static HashMap<String, String> DataDictionaryFromArray(
  String[][] arrayforDictionary, int iRow) {
  // Create a hashmap to store the data as dictionary in key value form
  HashMap<String, String> dictionary = new HashMap<String, String>();
  // get the size of the array, assuming being used in data driven test,
  // get the number of columns in the data file
  int iColCnt = arrayforDictionary[0].length;
  for (int i = 0; i < iColCnt; i++) {
   // mark the header column values as key and current column value as
   // key value pair
   dictionary.put(arrayforDictionary[0][i],
     arrayforDictionary[iRow][i]);
  }
  return dictionary;
 }
}

Sunday, July 10, 2016

Code to read data from excel file - Java Selenium Data Driven frameworks

In Data driven framework for automation testing, data is stored in external file and helper/utility classes are created to interact with the data stored in external file. Data is normally stored in excel or csv files. Storing data in excel file is convenient as data for multiple workflows/module can be stored in different sheets of the same workbook. In the last post,code explaining how to read data from a csv file was explained. Click here to understand how to read data from a csv file.


In this post, we will understand how to interact with excel file. To interact with excel file, we need to add external jar files. Two common external file to interact with excel are :

  • jxl.jar - Supports only xls format.
  • org.apache.poi - Support both xls and xlsx format.

Download the external Jar file and add in the build path for the project. Below code shows how to read data from excel file using jxl.jar 


package testingtest;

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

class excelarrayclass {

 static String[][] getexceldatainArray;

 public static void main(String[] args) throws IOException, BiffException {
  // Create an array based on data in excel file
  excelarrayclass tc = new excelarrayclass();
  getexceldatainArray = tc.CreateArrayfromExcel("D:\\Testing.xls",
    "testing");
 }

 public String[][] CreateArrayfromExcel(String WorkbookName, String SheetName)
   throws BiffException, IOException {
  String[][] arrTestDta;

  Workbook workbk = Workbook.getWorkbook(new File(WorkbookName));
  Sheet wrkSheet = workbk.getSheet(SheetName);
  arrTestDta = new String[wrkSheet.getRows()][wrkSheet.getColumn()]

  for (int i = 0; i < wrkSheet.getRows(); i++) {
   for (int j = 0; j < wrkSheet.getColumns(); j++) {
    Cell cell = wrkSheet.getCell(j, i);
    if (cell.getContents() != null) {
     arrTestDta[i][j] = cell.getContents();
     System.out.println(cell.getContents());
    }
   }
  }
  return arrTestDta;
 }

}

Saturday, July 9, 2016

Creating array from data in CSV file for Data driven tests in selenium

Two dimensional Array can be created from csv file using the below code to automate workflows in selenium Web-driver using data driven approach. Once data is stored in an array, the code need not to interact with external file again and again but will interact with the array or with data dictionary/hashmap created from the array. 

Code to create an array from CSV file:


package testingtest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

class testclass {

 static String[][] getcsvdatainArray;
    
 public static void main(String[] args) throws IOException {
  // Create an array based on data in a csv file
  testclass tc = new testclass();
  getcsvdatainArray = tc.createarrfromcsvfile("D:/testing.csv");
 }
 
 //get count of rows of data in the csv file
 private int getrowsfromcsv(String strFileName) throws IOException
 {
  InputStream inputfile = new FileInputStream(new File(strFileName));
     BufferedReader bfrReader = new BufferedReader(new InputStreamReader(inputfile));
     int rowscount = 0;
     while ( bfrReader.readLine() != null)
     {
      rowscount++;
     }
     System.out.println(rowscount); 
     bfrReader.close();  
     return rowscount;
 }
 
 //get count of column of data in the csv file
 private int getcolumnsfromcsv(String strFileName) throws IOException
 {
  InputStream inputfile = new FileInputStream(new File(strFileName));
     BufferedReader bfrReader = new BufferedReader(new InputStreamReader(inputfile));
     int columncnt = bfrReader.readLine().split(",").length ;
     bfrReader.close();
     return columncnt;
 }
 
 //create a 2 dimensional string array from the content of csv file
 public String[][] createarrfromcsvfile(String strFileName) throws IOException
 {
  //get rows and column count in the csv file
  int introwcount = getrowsfromcsv(strFileName);
  int intcolcount = getcolumnsfromcsv(strFileName);
  InputStream inputfile = new FileInputStream(new File(strFileName));
     BufferedReader bfrreader = new BufferedReader(new InputStreamReader(inputfile));
     String strrowdta,strrowinfo[];
     int rowcnt = 0;
     //create an array
     String[][]strDta = new String[introwcount][intcolcount];
     //store data in the array
     while ((strrowdta = bfrreader.readLine()) != null)
     {     
      strrowinfo = strrowdta.split(",") ;   
      for (int i = 0;i<strrowinfo.length;i++)
      {
       strDta[rowcnt][i] = strrowinfo[i];
       System.out.println(strDta[rowcnt][i]);
      }
      rowcnt++;     
     }
     bfrreader.close(); 
     return strDta;
 }
}


In another post,code explaining how to read data from a excel file was explained. Click here to understand how to read data from a excel file.

Tuesday, June 14, 2016

Understanding Locators in Selenium WebDriver and common element types

Locators are used to identify an element in the WebPage.  An object can be identified based on the attributes values.  In this article, we will discuss the different locators based on which an element can be identified in the page using selenium webdriver.


Locators are used to locate an element in the Page based on the unique address of the object in the Page. It can be unique attribute value, for e.g: id of the element or the absolute or relative xpath of the element in the Page. 


Once an object is identified in the Page, we can perform the required operation/action on the object. Below are the different common types of elements on the Page:


Common Elements Types
Type
Common Operations on Object Type
Anchor elements or links
Clicking on a link
Validating links in Page are correct or broken
Validating links exist in the Page
TextBox
Validating text box is available/enabled
Input data in the edit box
Radio Button
Selecting a radio button
Checkbox
Validating whether checkbox is selected or not.
Selecting/deselecting checkbox
DropDown
Selecting value from the dropdown
Labels
Extracting value from the label or validating label exist in the page.
Table
Extracting information from table.
Multi-Select ComboBox
Selecting multiple values from a combobox.


The different types of locators used to locate elements in selenium are described below:


Locator Types
Locator DefinitionUsage
IDelement matching "id" attribute of the element. Normally id of an element in the Page is expected to be unique. Hence if available, using id of the element is good option.
WebElement usr = driver.findElement(By.id("name"));
 Nameelement matching "name" attribute of the element. There may be multiple element with same name in Page. In such scenario, first element matching the name is selected.
WebElement usr = driver.findElement(By.name("uname"));
 Link Text
Partial Link text
For links in the Page, we can use linktext and partialLinkText to identify the links based on the name/Partial text of the link. Applicable for links element only

WebElement elem=driver.findElement(By.linkText("mail"));

driver.findElement(By.partialLinkText("mail"));
 CSS SelectorUsing CSS locators, we can identify elements. Both Xpath and CSS are useful and highly used in identifying elements in the Page.Absolute or relative Xpath can be created to identify element in the PageWebElement elem = driver.findElement(By.cssSelector("a.test"));
 XPathPlease refer to my previous post for details on xpath and css:
http://seleniumbites.blogspot.in/2016/01/xpath-and-css-for-selenium-webdriver.html
WebElement elem = driver.findElement(By.xpath("//input[@id='mail']"));
ClassNameClassName uses the class attribute of the element to locate the element. Foe e.g.: in case of identifying the random error message displayed in the Page, usually the message may have the same class attribute. We can create a collection of elements matching the class and gather the required error messages in the Pagedriver.findElement(By.className("errormessage"));
TagNameThis locator is useful while working with list of elements in the Page. E.g: Finding number of links in the PageList <WebElement> linklst = driver.findElements(By.tagName(“a”));

Friday, May 20, 2016

MindMap for Selenium WebDriver

In this mindmap, Basic and initial steps to start with selenium Webdriver are explained in the form of mindmap. Hope you like this mindmap to start with Selenium WebDriver.


MindMap for Selenium WebDriver


Saturday, March 12, 2016

Page Object Model pattern in Selenium?

Page Object Model in selenium is a design Pattern (Design Pattern is a general reusable solution(best practices) to a commonly occurring problem within the context in software design) implemented using selenium Web Driver. Page Object Model is used to create object repository for elements in the web application used in test flows.


Page Object Model Pattern serves following purposes:


  • Segregating objects definition from test scripts in separate classes making test scripts independent of page elements and locators, thus reducing the maintenance cost in case of changes in elements locator in the Application under test.
  • Defining Page elements and page methods in Page classes help in re-usability of the page elements and methods in different tests reduces the line of code and makes it more maintainable as changes in application needs to be implemented at Page classes only.
  • Make code more readable in the test scripts.
  • Easier for testers with less knowledge of selenium/Java to create test scripts once the Page classes are prepared.

Page Object Model - Do not see too seriously

Understanding how to automate a web application using selenium Web Driver using Page Object Model design pattern


Let us try to understand how Page object model pattern is implemented with an example. 


Suppose there are number of pages in an Web Application and within each page there are multiple elements in each page. Let us assume linear approach for creating automated test cases. Suppose there are ~100 test scripts(workflows) to test the application. Each of the workflow starts with login into application. In each of the test cases, we would have defined the locators for input fields for username and password and login button elements and interact(perform action) with the element. 


Creating test using above approach will result in following problems:
  • In case of changes in an element locator, changes needs to be implemented at multiple tests
  • Readability of test will be poor due to locators defined at test level. 
  • Lines of code will be higher and approach for creating test scripts will vary from one test developer to another.
  • Requires script developer to have good selenium knowledge for test scripts creation. 

Object repository structure in QTPA better approach would be to define elements locators at a different location from test scripts. Also methods for working with elements should be defined, separate of the test scripts.


If you had worked with QTP before, the object repository used to be maintained in tree structure. In Page Object model design pattern,Web Pages are represented by classes with elements in the Page defined as members of the class. Actions on the elements are implemented as methods in the class very much similar to QTP approach.



Implementing Page Object Model:


  • Create a class for login Page (similarly create class for different pages).
  • Define the objects locator in the Page as member of the class.
  • In the constructor method for the Page class, load or intialise the elements defined in the Page using Page Object Factory. 
  • Create user defined methods in the class to input data in the input box, clicking the login button, and methods for successful login or failure. 
  • An object of the page class will be created in the test scripts to interact with the objects and methods for Page class.
    Page Object model pattern implementation

I have not added any code snippet in this article, but below reference article have nice examples explaining the code and concept of Page Object model pattern in selenium.


Useful References for code and concept of Page Object Model

Hope you find this post informative or atleast the references useful.

Sunday, February 21, 2016

Maven POM.xml: Dependencies for Selenium, TestNG and junit

While working with Selenium, TestNG and junit with maven, we need to add in the Project Object Model (POM.xml), dependencies for Selenium, TestNG and junit. In this article, we have explained how to add the required dependency in the dependencies section in pom.xmlfile.

Add the dependency in the dependencies section for the required artifacts. Also please update the version as per latest version of the artifact.


Selenium Dependency:

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.52.0</version>
</dependency>

junit Dependency:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>

TestNG Dependency:

<dependency>
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>
  <version>6.8</version>
  <scope>test</scope>
</dependency>

Saturday, February 20, 2016

How to use maven to create selenium project

In this article, we will understand the basics of maven and how to create maven project for Selenium WebDriver in eclipse.

Problem Statement of this article:

  • Understanding the use of maven for creating a selenium Project.
  • Installing maven plug-in for eclipse
  • Creating a maven Project in eclipse
  • Adding dependencies for Selenium


Understanding the use of maven for creating a selenium Project.


  • Maven provides a uniform build system.
  • A Project Object Model or POM is an XML file in maven that contains project and configuration information used by Maven to build the project.
  • We can add and configure dependencies for selenium, TestNG and other resources in the maven Project using POM.xml file
  • Maven helps to define Project structure for better management of resources.
  • Maven automatically downloads the necessary files added in dependencies for WebDriver and other resources while building the project.


maven plugin download from eclipse

Installing maven plug-in for eclipse



Below are the steps to install maven plug-in for eclipse

  • Open eclipse and click on Help>Eclipse Marketplace
  • Search for Maven integration for Eclipse in eclipse marketplace. Install Maven integration for Eclipse
  • Restart eclipse.
  • Maven plug-in has been added in eclipse.


Creating a maven Project in eclipse:


  Pre-Condition: Maven Plug-in is added in eclipse.Below are the steps to create a maven project in eclipse.

creating maven project in selenium
  • Navigate to File>New>Project.
  • It will ask to select a wizard. Select Maven>Maven Project and click on Next
creating maven project in selenium
  • To start with, select create a simple project in the window and click on Next.
  • Provide the details for the artifact including Group Id, Artifact Id, Version, packaging to start with.
  • Click on Finish.
creating maven project in selenium

Once we click on finish,maven project is created in Java. As mentioned earlier, All the configurations of the Project are saved in a POM.xml file as shown below:

creating maven project in selenium


POM stands for "Project Object Model". It is XML representation of the Maven project. POM.xml file inherits from base superPOM.xml

How to use selenium libraries in the maven Project.


We can use selenium libraries by adding dependencies for selenium in the Project Object model as shown in the code snippet below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>qaautomation</groupId>
  <artifactId>Selenium_eclipse_maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>My first maven</name>
  <description>testing</description>  
  <dependencies>
      <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.48.2</version>
    </dependency>
    <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.8.1</version>
</dependency>    
  </dependencies>
</project>

References:




Saturday, February 6, 2016

Assertion and Soft Assertions in Selenium Webdriver using TestNG

We create automated regression test to validate the application is working correctly. We need to add checkpoints/validation at different steps in the workflow to validate the application is correctly behaving or not.

For e.g.: Let us consider login into an e-mail website. We need to go to application URL and assert/validate username and password input box and Login button are displayed correctly. Then next step can be to assert login is successful for a positive test with valid username and password or assert proper error message is displayed for a negative test with invalid username and password.

Testing framework for automation like TestNG and jUnit for Java or nUnit for C# provides feature of assertion to assert/validate the application is working properly and scores 10/10 in the test results.

In this article, we will discuss how to add assertions using TestNG framework for selenium tests.


Problem statements of this article:

  • What is meant by Assertions in TestNG?
  • What are different types of assertion in TestNG?
  • What is the difference between assert and softassertions?
  • Code explaining how to implement assert and softassert in TestNG?


What is meant by Assertions?

With TestNG framework, We can add assertions within tests to validate whether the expected condition is true or false. In most of the assertions, the expected condition is compared with the actual results and test fails in case an assertion fails. The failure is reported in test results.

For example in a selenium test for login functionality, When we provide valid username and password and login into application, we expect the title to be displayed correctly in the page. So in this scenario, we should add an assertion for comparing the expected title of the page with the actual title displayed in the page. In case, the two values does not match, the assertion fails and test execution fails 

What are different types of assertions?

Some of the assertions that can be implemented in TestNG are as follows:
Types of assertion
Description
Assert.AssertEquals(Expected condition, Actual condition)
This compares the expected condition with actual condition and fails the test in case the assertion fails.Different object types can be compared using Assert.AssertEquals
Assert.AssertEquals(Expected condition, Actual condition, Message)
This compares the expected condition with actual condition and fails the test in case the assertion fails displaying the message as defined while calling the assertion.
Assert.assertFalse(Boolean condition)
Asserts that a condition is false
Assert.assertFalse(Boolean condition, String Message )
Asserts that a condition is false. If it isn't, an Assertion Error, with the given message, is thrown.
Assert.assertTrue(Boolean condition, String Message )
Asserts that a condition is true. Assertion fails if condition is not true and string message is displayed.
Assert.AssertNull(object)
Validates if a assertion is null.
Assert.Fail(String strMessage)
Fails an assertion without validating any conditions. This is very useful for outcome of conditional statements. e.g: if title is incorrect, fail the test.



Sample Code to explain how to create assertion in TestNG

package testNG;  
 import java.io.File;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 import org.testng.Assert;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.Test;  
 public class assertionVal {  
      WebDriver driver;  
      @BeforeTest  
      public void setup()   
      {  
           File file = new File("D:\\selenium\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           driver = new InternetExplorerDriver();  
      }  
      @Test  
      public void assertVal()   
      {  
           driver.navigate().to("http://qaautomationqtp.blogspot.com");  
           Assert.assertEquals("Learning Automation Concepts in QTP", driver.getTitle());  
           //Assert to compare two values and reporting a message in case validation fails  
           Assert.assertEquals("aaa", "aaa", "this is the first test and value does not match");  
           //Assert to validate a boolean condition as false   
           Assert.assertFalse(driver.getTitle().contentEquals("Learning Automation Concepts in QTP"));  
           //Assert to validate a boolean condition as true   
           Assert.assertFalse(driver.getTitle().contentEquals("Learning Automation Concepts in QTP"));  
        //Assertion to validate an object is not null.  
        Assert.assertNotNull("driver");  
      }  
 }  


What is the difference between assert and soft assertions (Verify statements)?

The issue with assertion is, test execution stops in case an assertion fails. So if we do not want to stop a test on failure and continue with test execution, using assert statement will not work, 
In such sccnarios, we will use soft assertions, using  import org.testng.asserts.SoftAssert; class.
In this case, verification step will fail but test execution will continue. 

Sample Code to explain how to implement soft assertion in TestNG



 package testNG;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 //soft assertion will use the below softAssert class  
 import org.testng.asserts.SoftAssert;  
 public class assertionVal {  
      // Create an soft assertion object softas   
      SoftAssert softas = new SoftAssert();  
      @Test  
      public void assertVal()   
      {  
           //Create an assertion similar to hard assertion as shown below   
           softas.assertEquals("aaaa", "bb");  
           softas.assertEquals("aa","aaccc","asserts exists");  
           // this is an example of hard assertion, test will stop execution   
           //at this step in case error is encountered.  
           Assert.assertEquals("aa", "aa");  
           System.out.println("nitin");  
           //This step is very important as without this step,  
           //no soft assertion failure will be reported in test result.  
           softas.assertAll();  
      }  
 }