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:

 

Saturday, February 6, 2016

Paros - Simplest way to secure your Web Application


http://qabypassion.blogspot.in/2010/08/paros-simplest-security-tool.html

Note: Right now no development happening on Paros. It won't work on latest java. You can use Zed Attack Proxy (ZAP) if 64 bit java and latest versions were installed on your system.

TestNG

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

Introduction: 


The TestNG Eclipse plug-in allows you to run your TestNG tests from Eclipse and easily monitor their execution and their output. TestNG with WebDriver provides an efficient and effective test result format that can in turn be shared with the stake holders to have a glimpse on the product’s/application’s health thereby eliminating the drawback of WebDriver’s incapability to generate test reports. TestNG has an inbuilt exception handling mechanism which lets the program to run without terminating unexpectedly.

Steps to Install TestNG Eclipse Plugin 


1.       Launch the Eclipse IDE.

2.       Click “Help” -> “Install New Software …”.

 
3. Click “Add” button
 
 
4.  Enter Name as “TestNg” and Location as “http://beust.com/eclipse”.
 
5. Now, click “OK” button then “Next >” button.
 
6. Click Finish button by selecting the radio button “I accept the terms of the license agreement” and then click “Finish” button.
7. To check whether TestNG is installed in Eclipse, go “File” menu à “New” à “Other…”
Like JUnit, TestNG is also a testing framework which uses annotations,  but with  some new functionalities that make it more powerful and easier to use, such as:
Ø  Annotations.
Ø  Run your tests in arbitrarily big thread pools with various policies available (all methods in their own thread, one thread per test class, etc...).
Ø  Test that your code is multithread safe.
Ø  Flexible test configuration.
Ø  Support for data-driven testing (with @DataProvider).
Ø  Support for parameters.
Ø  Powerful execution model (no more TestSuite).
Ø  Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc...).
Ø  Embeds BeanShell for further flexibility.
Ø  Default JDK functions for runtime and logging (no dependencies).
Ø  Dependent methods for application server testing. 
As we discussed above, We will learn how the TestNG with WebDriver provides an efficient and effective test result report.
Let us see a simple program:
The following example, the Java class contains two test cases (methods) “testLogin” and “testRegister”.  
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; 
public class LoginTest {
       @BeforeTest
       public void testOpenConnections() {
              System.out.println("Connectedt to Database");        
       }
    @AfterTest
       public void testCloseConnection() {
              System.out.println("DB connection closed");     
      }
    @BeforeMethod
    public void testOpenBrowser() {
    System.out.println("Browser Open ...");
    }
    @AfterMethod
       public void testCloseBrowser() {
      System.out.println("Browser closed ...");
    }
   @Test
   public void testLogin() { 
    System.out.println("Login Page");
       }
  @Test
  public void testRegister(){
System.out.println("Register Page");
    }
}
For run the above Java Code, Right Click on the Code File à Run as TestNG Test.
 
 
On successful execution, TestNG will create a report folder which will provide the report in Html file
 
 

 
Open the “index.html” file, TestNG test case execution report will be displayed.
 
 

 

Run multiple test cases:

Continuation to  the above example, We will create a test case which test the following test scenario.
i.e., The system should allow to sell the item only if the user logged-in. If the condition fails, then system should skip the method to execute.
Here, we’ll create a class “SellItems.java” which contains the methods “testSellItems()”, “shouldbeSKIP()”  and “isLogedIn()”.
Now, we will run both case test cases sequentially. 
Code:
import org.testng.SkipException;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public class SellItems {      
       @BeforeTest
       public void shouldbeSKIP() {
              //check whether the user is loged in or not
              if(!isLogedIn()) {
                     throw new SkipException("Skipping because User is not loged in");
              }
       }
      
       @Test
       public void testSellItems() {
              System.out.println("Sell the Items ... ");
       }
      
       public boolean isLogedIn() {             
              return false;
       }
 
}
 
SellingItems():  System allows the user to sell the items.
isLogedIn():  Cross-checks the user logged in or not.
shouldbeSKIP() : Do not allow the user to user to sell Items if “isLogedIn()” returns “false”. 
For running multiple classes or test cases in sequence, we have to configure the Java classes in an XML. So, create and XML (Ex. TestNG.xml) under project hierarchy.
 
TestNG.xml:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> 
<suite name="my sample test">
       <test name="Application Login">
              <classes>
                     <class name="LoginTest"></class>
              </classes>
       </test> 
       <test name="Selling Items">
              <classes>
                     <class name="SellItems"></class>
              </classes>
       </test>
</suite>  
Run the TestNG suite:
 
 
 
 
Step1: “Right Click” on “TestNG.xml” file in Package Explorer.
Step2: Select “Run As”.
Step3: Click “1 TestNG Suite”.
After click on “TestNG Suite”, first LoginTest.java will execute and then SellItems.java will be executed.
REPORT:

 


Results of Running Suit: