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

Friday, March 18, 2016

PAGE OBJECT MODEL


Posted by: Kiran Thurimerla
 (SQA Module Lead working at Ebix Software India PVT Ltd).
Contact Author: kiran.thurimerla@gmail.com

Creating Selenium test cases can result in not maintainable project. One of the reasons is that too many duplicated code is used. Duplicated code could be caused by duplicated functionality and this will result in duplicated usage of locators. The disadvantage of duplicated code is that the project is less maintainable. If some locator will change, you have to walk through the whole test code to adjust locators where necessary. By using the page object model we can make non-brittle test code and reduce or eliminate duplicate test code. Beside of that it improves the readability and allows us to create interactive documentation. Last but not least, we can create tests with less keystroke. An implementation of the page object model can be achieved by separating the abstraction of the test object and the test scripts.

Example (General):

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.ie.InternetExplorerDriver;

 

public class SampleOne {

      

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

 

              System.setProperty("webdriver.ie.driver",".\\IEDriverServer.exe");

             

              WebDriver driver = new InternetExplorerDriver();

             

              driver.get("http://obesityfoundationindia.com/bmi.htm");

             

              WebElement wt = driver.findElement(By.name("wg"));

              wt.sendKeys("68");

             

              WebElement kglbs = driver.findElement(By.name("opt1"));

              kglbs.sendKeys("kilograms");

             

              WebElement hft = driver.findElement(By.name("opt2"));

              hft.sendKeys("5'");

             

              WebElement hinc = driver.findElement(By.name("opt3"));

              hinc.sendKeys("9\"");

             

              WebElement cal = driver.findElement(By.name("cc"));

              cal.click();

             

              Thread.sleep(3000);

              driver.quit();

       }

 

}

 In the above code, the Web elements declarations are not reusable. If we want to build any other scenarios with the same elements we need to once again write all the objects declarations.

Using Page Object Model (POM), we can reuse the web elements declarations.  In POM, we will separate Web elements declarations from main selenium scripting file so that, the same web elements declarations will be reusable in other scripts.

It’s just like an Objects Repository.  For each web page we will write a separate object repository file which contains all the Web elements objects.

In the above given example, all the web elements are given in a single file.  But, as per POM, we will a separate objects repository file.
 
 
Example (POI): ( Screenshot1)

 
 

Main Scripting class: (Screenshot2)
 
 
 
 
Example (POI): (Code)
package pageObjects;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
public class BMICalcHome {
 
       //wt, kglbs, hft, hinc, cal
      
       public static  WebElement wg(WebDriver driver) {
             
              WebElement wt = driver.findElement(By.name("wg"));
              return wt;
       }
      
       public static WebElement kglbs(WebDriver driver) {
             
              WebElement kglbs = driver.findElement(By.name("opt1"));
              return kglbs;
       }
      
       public static WebElement hft(WebDriver driver) {
             
              WebElement hft = driver.findElement(By.name("opt2"));
              return hft;
       }
      
       public static WebElement hinc(WebDriver driver) {
             
              WebElement hinc = driver.findElement(By.name("opt3"));
              return hinc;
       }
      
       public static WebElement cal(WebDriver driver) {
             
              WebElement cal = driver.findElement(By.name("cc"));
              return cal;
       }
}
 
Main Scripting class: (Code)
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
 
import pageObjects.BMICalcHome;
import pageObjects.BMIMemberReg;
 
public class POM_Samp1 {
 
       public static void main(String[] args) throws InterruptedException {
              // TODO Auto-generated method stub
             
              System.setProperty("webdriver.ie.driver",".\\IEDriverServer.exe");
             
              WebDriver driver = new InternetExplorerDriver();
             
              driver.get("http://obesityfoundationindia.com/bmi.htm");
             
      
              //Home Page
             
              BMICalcHome.wg(driver).sendKeys("75");
              BMICalcHome.kglbs(driver).sendKeys("kilograms");
              BMICalcHome.hft(driver).sendKeys("5'");
              BMICalcHome.hinc(driver).sendKeys("9\"");
              BMICalcHome.cal(driver).click();
             
              Thread.sleep(3000);
              driver.quit();
 
       }
 
}
 
 

 

Tuesday, February 23, 2016

Writing data to spreadsheet using poi

  1. Create a project and package
  2. Download the"poi-3.13"
  3. Add the "xmlbeans" jar and the "poi" jars.
  4. This example reads the data from a spreadsheet and once reading is done, writes the data “ReadingDone” in last column
  5. In this example, spreadsheet resides at D:\Hemanth\TestData\TestData.xlsx

 
Sample Program:
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadMain {
 public static void main(String[] args) throws Exception {

  File source = new File("D:\\Hemanth\\TestData\\TestData.xlsx");
  FileInputStream fis = new FileInputStream(source);
  XSSFWorkbook wb = new XSSFWorkbook(fis);
  int FirstRow = wb.getSheet("Sheet2").getFirstRowNum();
  int FirstCol = wb.getSheet("Sheet2").getRow(FirstRow).getFirstCellNum();
  System.out.println("FirstRow:"+FirstRow);
  System.out.println("FirstCell:"+FirstCol);
  int Lastrow = wb.getSheet("Sheet2").getLastRowNum();
  System.out.println("LastRow:" +Lastrow);
  int Lastcol = wb.getSheet("Sheet2").getRow(Lastrow).getLastCellNum();
  System.out.println("LastCol:" +Lastcol);
  String activecell = wb.getSheet("Sheet2").getActiveCell();
  System.out.println("Active Cell:" + activecell);
  ArrayList mylist = new ArrayList();
  String Value;

  for (int i=0;i<=Lastrow;i++)
  {
   for(int j=0;j<Lastcol;j++)
   {
    Value = wb.getSheet("Sheet2").getRow(i).getCell(j).getStringCellValue();
    System.out.println("Read Value:"+Value);
    mylist.add(Value);
 
   }

   wb.getSheet("Sheet2").getRow(i).createCell(Lastcol).setCellValue("ReadingDone");
  }

    System.out.println("Values:"+mylist);
   FileOutputStream fos = new FileOutputStream(source);
 
   wb.write(fos);
    wb.close();  
 
 }

}
 
Result:
 
 
 

Sunday, February 21, 2016

Taking a Screenshot - Selenium WebDriver

  • Create a Project and package
  • Add Selenium jar
  • In this example, we are taking the screenshot of a webpage and saving that with the timestamp and as a .png file in preferred location(In this example, D:\Hemanth\Screenshots folder)

Example:

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class TakeScreenshot {

  @Test

  public void myTest() throws Exception {

  WebDriver driver;
        driver = new FirefoxDriver();
        driver.get("http://stlc4u.blogspot.in");
        driver.manage().window().maximize();
       
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateN = dateformat.format(currentDate.getTime());
        System.out.println("Date:" + dateformat);
        String filename = "screenshot"+dateN+ ".png";
        File destinationFile = new File("D:\\Hemanth\\Screenshots\\"+ filename);
        FileUtils.copyFile(screenshot, destinationFile);
        driver.close();     
      
    }
}


Screenshot Path and Name:



Output:
 

Reading data from spreadsheet

  • Create a project and package
  • Download the"poi-3.13"
  • Add the "xmlbeans" jar and the "poi" jars.
  • Create a test data spreadsheet (In this example, path of spread sheet is D:\Hemanth\TestData\TestData.xlsx" and fill any one sheet with the data)
  • In the below example, path of the spreadsheet is given as "source"
  • workbook(wb) was read
  • Identified the first row, first column(cell), last row and last column
  • Data was added to the ArrayList using For loops
  • Printed the ArrayList data.
Example Spreadsheet:

Example Code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadMain {
 public static void main(String[] args) throws Exception {

  File source = new File("D:\\Hemanth\\TestData\\TestData.xlsx");
  FileInputStream fis = new FileInputStream(source);
  XSSFWorkbook wb = new XSSFWorkbook(fis);
  int FirstRow = wb.getSheet("Sheet3").getFirstRowNum();
  int FirstCell = wb.getSheet("sheet3").getRow(FirstRow).getFirstCellNum();
  System.out.println("FirstRow:"+FirstRow);
  System.out.println("FirstCell:"+FirstCell);
  int Lastrow = wb.getSheet("Sheet3").getLastRowNum();
  System.out.println("LastRow:" +Lastrow);
  int Lastcol = wb.getSheet("Sheet3").getRow(Lastrow).getLastCellNum();
  System.out.println("LastCol:" +Lastcol);
  String activecell = wb.getSheet("Sheet3").getActiveCell();
  System.out.println("Active Cell:" + activecell);
  ArrayList mylist = new ArrayList();
  String Value;

  for (int i=0;i<=Lastrow;i++)
  {
   for(int j=0;j<Lastcol;j++)
   {
    Value = wb.getSheet("Sheet3").getRow(i).getCell(j).getStringCellValue();
    System.out.println("Read Value:"+Value);
    mylist.add(Value);
   }
 
  }

    System.out.println("Values:"+mylist); 
 }

Output:

 

Wednesday, February 3, 2016

Reports generation with Selenium, JUNIT and ANT

 


Step1: Create two classes with first class having two test cases, second having one test case.  Create ”MyTestSuite”.


 

Step2: Go to Windows>Preferences and add the "JUNIT" jar through external jars as shown below.





Step3: On TestCases package, right click and select Export option
 
 

Step4: Select “ANT Build Files” and click Next
 
 
Step5: Select the project name and click “Finish”, The Build.xml file will be generated.

 
 

Step6: Open the build.xml and remove the Target xml section created for the first two classes. Don’t remove the MyTestSuite related Target. Save the file.
Step7: Right click on build.xml, select “Run As” and “Ant Build” option
 
Step8: Select “build[default], MyTestSuite, juintreport” and click “Run”.
 
Step9: MyTestSuite executes and report will be available in “junit” folder.
 
Step10: Open “Index.html” in Web Browser.
 
Step11: Click on “MyTestSuite” for detailed results.