Saturday, July 30, 2016

Quick Codes- Validating element existence in Selenium Wedriver


In this article, one of the way to validate existence of multiple objects of same object type based on element text in the application is explained using Selenium Webdriver with java. Please share other better way to verify element existence using Selenium Webdriver.


public boolean IsElementExists(String ObjectType, String strElemText)
{
 boolean boolElemExists = false;
//In case of multiple objects which needs to be validated, Provide multiple objects
// text seperated by  | in strElemText. e.g: strElemText as "mail|inbox"
// Create an array by splitting array based on delimiter "|"
 String[] elemTextArray = strElemText.split("|");
// Loop through array elements
 for ( int j = 0;j<elemTextArray.length;j++)
 {
  List<WebElement> lstElement = null;
  try
// Better approach will be to pass values from enum for Object type
   switch (ObjectType)
   {
   // in case of link object storing all the elements of type link in lstElement
   case "Link":
     lstElement = driver.findElements(By.tagName("a")); 
    break;
    // in case of link object storing all the elements of type link in label
   case "Label":
    lstElement = driver.findElements(By.tagName("label")); 
    break;
   }
   for (int i=0;i<lstElement.size();i++)
   {
    if (lstElement.get(i).getText().contentEquals(strElemText.trim()))
      {
       boolElemExists = true;
       i= lstElement.size()-1;
      }
   }
   if (boolElemExists = false)
   {
    return false;
   }
   }
  catch(Exception e)
  {
   return false;
  }
 }
 return boolElemExists;
}

Tuesday, July 26, 2016

Quick Codes -How to highlight element using Selenium WebDriver

This code snippet shows one of the way to highlight an element using JavaScript executor in Selenium WebDriver. Please share your inputs on other ways to highlight an element using Selenium.



package testingqaautomation; 

import org.junit.Test;
import org.openqa.selenium.By;  
import org.openqa.selenium.JavascriptExecutor;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.firefox.FirefoxDriver;  
 
 public class HighlightWithJE {  
      static WebDriver driver; 
      @Test
      public void Testing() throws InterruptedException {  
  // Connect to the firefox driver server 
  driver = new FirefoxDriver(); 
  //maximise the browser   
  driver.manage().window().maximize();   
  //Navigate to the application, change url to a valid url
  driver.navigate().to("https://www.seleniumbites.blogspot.com");  
  //find element to highlight, select a valid element
  WebElement linkElem = driver.findElement(By.linkText("Gmail"));  
  //create instance of javascript executor
  JavascriptExecutor js = (JavascriptExecutor) driver; 
  //highlight the element to green color and wait
  //for 3 sec and then click the element
  js.executeScript("arguments[0].setAttribute('style','border: solid 8px green')", linkElem);   
  Thread.sleep(3000);  
  js.executeScript("arguments[0].setAttribute('style', arguments[1]);", linkElem, "");  
  linkElem.click();            
      } 
}   

Saturday, July 23, 2016

Installing TestNG in eclipse


TestNG is a testing framework used to design automated functional/unit tests in Java. Eclipse is one of the most popular IDE for developing tests in Java. In this article, we will understand how to set up/install testNG with Eclipse.


A. Launch Eclipse IDE and Navigate to Help>Install new Software. A pop-up page with title as Install will be displayed.


B. Set http://beust.com/eclipse in Work With Input box and click on Add Button.


C. Checkbox for TestNG is displayed in the Page. Select checkbox and click on Next.


D. Agree to the license agreement.


E. Software download will begin and TestNG will be installed.


F. Once TestNG installation is done, a pop-up window will be displayed asking to restart eclipse for changes to take place. Click on Yes to complete TestNG installation



Installing testNG in eclipse


Another way to install TestNG in eclipse is to navigate to Help>Eclipse Marketplace and search for TestNG. Install TestNG from the search results.


Installing testNG in eclipse marketplace

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.