Wednesday, April 15, 2015

Properties File Reading For SeleniumWebDriver

For testing purpose we need some data from user at run time.It can be provided from external file.There is a way a to do that using properties file.

Basically properties file is holding data in key value pair. Properties file may be in .xml format or in .properties format.

Simple Properties File Looks Like below

User.Name="TestUser"
User.Password="TestPassword"


Here User.Name is as Key And "TestUser" is as value.

Xml Properties file looks like below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="User.Password">"TestPassword"</entry>
<entry key="User.Name">"TestUser"</entry>
</properties>


Here <entry key="User.Password"> key is "User.Password" and Value is "TestPassword"

Reading a properties file we need to initialize first 
        Properties prop=new Properties();

Then we need to load properties file according to the properties file type if it is normal properties then use this :
        prop.load(new FileInputStream("./propertiesFile.properties"));

or if properties file is xml then use
        properties.loadFromXML(new FileInputStream("./propertiesFile"));


Now we get the value from properties file using this code.

        System.out.println(properties.get("User.Name"));
        System.out.println(properties.get("User.Password"));


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package propertiesfilehandling;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesFileHandling {

    public static void main(String[] args) throws IOException {
        // Reading XML Properties File
        Properties properties=new Properties();
        properties.loadFromXML(new FileInputStream("./propertiesFile"));
        System.out.println(properties.get("User.Name"));
        System.out.println(properties.get("User.Password"));
       
        // Reading Properties File
        Properties prop=new Properties();
        prop.load(new FileInputStream("./propertiesFile.properties"));
        System.out.println(prop.get("User.Name"));
        System.out.println(prop.get("User.Password"));       
    }   
}




Friday, April 3, 2015

Different Type Of Annotation In Page Facory

Previously we use some annotation in Page Factory model to identify webelement.Here we learn some more different type of annotation in Selenium WebDriver for Page Factory pattern.

1.@FindBy

We can either use this annotation by specifying both "how" and "using" or by specifying one of the location strategies (eg: "id") with an appropriate value to use. Both options will delegate down to the matching By methods in By class. For example, these two annotations point to the same element :

                      @ FindBy(name = "q") 
                           WebElement search; 

                      @FindBy(how = How.Name, using = "q") 
                            WebElement search;

and these two annotations point to the same list of elements:

                      @FindBy(tagName = "a") 
                            List<WebElement> links; 
                      
                       @FindBy(how = How.TAG_NAME, using = "a") 
                             List<WebElement>
2.@FindAll
              @FindAll can contain multiple @FindBy and will return all the elements which matches any @FindBy in a single list.

3.@FindBys
             

                It is use to indicate that lookup should use a series of @FindBy tags in a chain. Mechanism used to locate elements within a document using a series of other lookups. This class will find all DOM elements that matches each of the locators in sequence, e.g.

                         driver.findElements(new ByChained(by1, by2))

will find all elements that match by2 and appear under an element that matches by1.Syntax to use FindBys is like that 
                               @FindBys({@FindBy(id = "gb119"),
                                                   @FindBy(name = "q")})


                                     
                                           WebElement search;
 In @FindBys it can return multiple WebElement it depends upon our use of @FindBy tag if It return multiple element then syntax should be looks like below

                               @FindBys({@FindBy(id = "gb119"),
                                                   @FindBy(name = "q")})

                                     
                                           List<WebElement> search;



4.@CacheLookup:
             We may use same WebElement repetitively on the same page and whenever we try to access this element, Selenium WebDriver again find this element on the page newly. But it does not require to find every time if this element is not an Ajax element or it is not used in any other page. If it is used in different page then name of this element may be same but element is different from previous one. So if we use this annotation for any particular WebElement then once Selenium WebDriver find this element again it will not try to find this element into the page.
                             
                             @FindBy(name = "q")})
                             @CacheLookup

                                         List<WebElement> search;



We can understand better in the below code :


//*************************************** 
// GOOGLEPAGE Class
//***************************************
 
package testng;

import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.PageFactory;

public class Google {

    /**
     * *****************************************************************
     * Here we use @FindBy(name="q") to identify the search WebElement We can
     * use this syntax also @FindBy(how = How.NAME, using= "q")
     *
     * @CacheLookup is used to cached the webelement.Using this WebDriver not
     * try to find everytime this element,Once it find it will store for future
     * reference. @CacheLookup can be used with @FindBys or @FindAll
     */

    @FindBy(name= "q")
            @CacheLookup
        WebElement searchUsingFindBy;


    /**
     * ****************************************************************
     * For FindBys it is not necessary that to find element We always follow the
     * full DOM Path.So name="q" may be the next under of the other element but
     * we can use any of the ancestor.
     */

    @FindBys({
        @FindBy(id = "tsf"),
        @FindBy(name = "q")})

    WebElement searchUsingFindBys;

    /**
     * *****************************************************************
     * For FindAll it return all matching Element but it does not give any
     * guaranty to maintain any order to return element.So may be @FindBy(name =
     * "q") store as first WebElement into the list and
     * @FindBy(id = "gb119") is last one.
     */

    @FindAll({
        @FindBy(id = "gb119"),
        @FindBy(name = "q")})
    List<WebElement> searchUsingFindAll;

    public Google sendTxtFindBys(WebDriver driver) {
        searchUsingFindBys.clear();
        searchUsingFindBys.sendKeys("Test By FindBy");
        return PageFactory.initElements(driver, Google.class);

    }

    public Google sendTxtFindBy(WebDriver driver) {
        searchUsingFindBy.clear();
        searchUsingFindBy.sendKeys("Test By FindBys");
        return PageFactory.initElements(driver, Google.class);

    }

    public Google sendTxtFindAll(WebDriver driver) {
        for (WebElement search : searchUsingFindAll) {

        // searchUsingFindAll holds other WebElement also.This checking
        // is required to send text for search field only.

           

            if (!search.getAttribute("name").trim().isEmpty()) {
                search.clear();
                search.sendKeys("Test By FindAll");
            }
        }
        return PageFactory.initElements(driver, Google.class);

    }

}


//***************************************
// Test Class
//***************************************

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import testng.Google;

public class GooglePageTest {

    WebDriver driver = null;

    @BeforeTest
    public void testSetUp() {
        driver = new FirefoxDriver(new FirefoxBinary(new File("G:/Program Files/Mozilla Firefox/firefox.exe")), new FirefoxProfile());
        driver.get("http://www.google.com");
    }

    // Test SearchField for Google Page Using @FindBy
    @Test
    public void testFindBy() {

        Google google = PageFactory.initElements(driver, Google.class);
        google.sendTxtFindBy(driver);

    }

    // Test SearchField for Google Page Using @FindBys
    @Test
    public void testFindBys() {

        Google google = PageFactory.initElements(driver, Google.class);
        google.sendTxtFindBys(driver);

    }

    // Test SearchField for Google Page Using @FindAll
    @Test

    public void testFindAll() {

        Google google = PageFactory.initElements(driver, Google.class);
        google.sendTxtFindAll(driver);

    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }

}


Saturday, February 7, 2015

Wait in Page Factory

We know that in Selenium WebDriver already have implicit and explicit wait,it is required to wait for an element until some condition is satisfied or to check that element is loaded or not.

In Page Factory model  there is AjaxElementLocatorFactory class by which we can implement another type of waiting technique for web element, it is basically behave same as implicit wait.

We can initialize AjaxElementLocatorFactory into the constructor by which we can avail the wait facility on all WebElements in the same page object class . It is basically used where application have more Ajax component Elements.

Example code is given below
  //***************************************
  // BLOGPAGE Class
  //*************************************** 

package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;

public class BlogPage {

    @FindBy(name = "txtbox1")
    private WebElement inputBox;
    @FindBy(name = "btnsub")
    private WebElement submitBtn;
    @FindBy(linkText = "Google")
    private WebElement googleLink;
    private final WebDriver driver;

    public BlogPage(WebDriver driver) {
        this.driver = driver;

        //  Wait 20 Second To Find Element If Element Is Not Present
        PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
    }

    public BlogPage submitForm(String inputTxt) {
        inputBox.sendKeys(inputTxt);
        return new BlogPage(driver);
    }

    public GooglePage clickOnGoogleLink() {
        googleLink.click();
        return new GooglePage(driver);
    }
}
 

  //***************************************
  // GOOGLEPAGE Class
  //***************************************
package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;

public class GooglePage {

    private final WebDriver driver;
    @FindBy(name = "q")
    WebElement searchTxtBox;

    public GooglePage(WebDriver driver) {
        this.driver = driver;

        //  Wait 20 Second To Find Element If Element Is Not Present
        PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
    }

    public GooglePage searchTxt(String searchTxt) {
        searchTxtBox.sendKeys(searchTxt);
        return new GooglePage(driver);
    }
}


  //***************************************
  // Test Class
  //**************************************
package com.core.pageobject;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class PageObjectModelTest {

    WebDriver driver;

    @BeforeTest
    public void testSetUp() {
        FirefoxBinary bin = new FirefoxBinary(new File("G:\\Program Files\\Mozilla Firefox\\firefox.exe"));
        FirefoxProfile prof = new FirefoxProfile();
        driver = new FirefoxDriver(bin, prof);
    }

    @BeforeMethod
    public void testMethodSetUp() {
        driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
    }

    @Test
    public void testSubmit() throws Exception {
        BlogPage blog = new BlogPage(driver);
        blog.submitForm("Test");
    }

    @Test
    public void testGoogleLink() throws Exception {
        BlogPage blog =new BlogPage(driver);
        blog.clickOnGoogleLink().searchTxt("Test");
    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}

Saturday, January 17, 2015

PageFactory In Selenium WebDriver

PageFactory is a way to implement Page Object Model in Selenium Webdriver.

In PageFactory mainly there are two things

1. PageFactory.initElements Method
2. @FindBy annotation

There are lots of other annotation(Like @FindAll,@FindBys,@Cache etc ) which we will learn later.


1. PageFactory.initElements Method

initElements are static methods of PageFactory class.

If we use this methods then we can assign value to the webelement at runtime when it is required. That means class loaded with WebElements having  some proxy(garbage or default) value and when actually it is required ,means call form method or accessing the WebElement in any way then it will find the WebElement into the page and assign the actual value to this WebElement. initelements method only assign value to the WebElement which is required currently it is not load the all webelement which is declared in page object class.

2. @FindBy annotation

Used to mark a field on a Page Object to indicate an alternative mechanism for locating the element or a list of elements. This allows users to quickly and easily create PageObjects.
You can either use this annotation by specifying both "how" and "using" or by specifying one of the location strategies (eg: "name") with an appropriate value to use.

e.g
 @FindBy(name = "q") 
  WebElement searchTxtBox;
 
 @FindBy(how = How.NAME, using = "q") 
  WebElement searchTxtBox;
 
Example Code is given below:
 
  //***************************************
  // BLOGPAGE Class
  //*************************************** 

package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class BlogPage {
 
  //***************************************
  // Use @FindBy Annotation To Locate Elements
  // Within Blog Page
  //***************************************  
    @FindBy(name = "txtbox1")
    private WebElement inputBox;
    @FindBy(name = "btnsub")
    private WebElement submitBtn;
    @FindBy(linkText = "Google")
    private WebElement googleLink;
 
    private final WebDriver driver;

    public BlogPage(WebDriver driver) {
        this.driver = driver;
    }
  //***************************************
  // BlogPage Have A Submit Button After
  // Click On That It Stay On Same Page So
  // Return Same Page Object
  //*************************************** 
 
    public BlogPage submitForm(String inputTxt) {
        inputBox.sendKeys(inputTxt);
        submitBtn.click();
        return PageFactory.initElements(driver, BlogPage.class);
    }
  //***************************************
  // BlogPage Have A Google Page Link After
  // Click On That It Redirect To Google Page
  // So Return Google Page Object
  //***************************************  
 
    public GooglePage clickonGoogleLink() {
        googleLink.click();
        return PageFactory.initElements(driver, GooglePage.class);
    }
}
 
  //***************************************
  // GOOGLEPAGE Class
  //***************************************
 
package com.core.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class GooglePage {
 
  //***************************************
  // Use @FindBy Annotation To Locate Elements
  // Within Google Page
  //***************************************  
    
    private final WebDriver driver;
    @FindBy(name = "q")
    WebElement searchTxtBox;

    public GooglePage(WebDriver driver) {
        this.driver = driver;
    }
 
  //***************************************
  // Searching Anything On Google Page remain
  // on Same Google Page So Return Type Is
  // Google Page Object.
  //*************************************** 
 
    public GooglePage searchTxt(String searchTxt) {
        searchTxtBox.sendKeys(searchTxt);
        return PageFactory.initElements(driver, GooglePage.class);
    }
} 
 
  //***************************************
  // Test Class
  //***************************************

package com.core.pageobject;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class PageObjectModelTest {

    WebDriver driver;

    @BeforeTest
    public void testSetUp() {
        FirefoxBinary bin = new FirefoxBinary(new File("G:\\Program Files\\Mozilla Firefox\\firefox.exe"));
        FirefoxProfile prof = new FirefoxProfile();
        driver = new FirefoxDriver(bin, prof);
    }

    @BeforeMethod
    public void testMethodSetUp() {
        driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
    }

    @Test
    public void testSubmit() throws Exception {
        BlogPage blog = PageFactory.initElements(driver, BlogPage.class);
        blog.submitForm("Test");
    }

    @Test
    public void testGoogleLink() throws Exception {
        BlogPage blog = PageFactory.initElements(driver, BlogPage.class);
        blog.clickonGoogleLink().searchTxt("Test");
    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}

 
 
We can create a another pageobject class for google search result here we make 
one pageobject class for google page and google search result.

Saturday, December 27, 2014

Page Object Model In Selenium WebDriver

What Is Page Object Model :

 Page Object Model is nothing but a code organization structure by which we can separated the web pages and Test classes.

Rule To Making This Structure :

 1. Separate the Test classes to WebPage classes.

 2. Create page related functionality on the same Page Class, from where we can perform functionality of this pages.

 3. If we perform any action on the page and redirect to the the another page, this method return type should be the another page object rather than void.If It stay on the same page then return the same page object or void.
               
     e.g : We can consider two page TestPage1 and TestPage2 for this example. 
TestPage1 and TestPage2 hold different component like button,image,checkbox,dropdown etc.Now we do some operational or structural work on this components like click,select etc to perform a logical or functional operation like login, sighout etc. After any individual logical or functional operation if we stay on the same page then this operation(method) return the same page object or void otherwise return the page object where it is redirected.

4. Isolate the Assertion(Pass,Fail) from the page classes and put them into test classes.

5. Page classes only hold the services that we can expect from this page.

6.Try to Exception handling into the test class.

Code Sample:

We have two page 

1. Blog Test Page
2. Google Search Page


We navigate Google search page from google link on Blog Test Page and give some text search on google page.So we must have 2 different class.BlogPage and GooglePage.

In BlogPage we have one operation click on google link which will navigate to the google page so this method return type should be google page object.But submit button on this page does not navigate to any other page it stay on this page so it's return type should be the blogpage object.

We follow the same structure in googlepage class also. 
  


Blog Test Page
---------------------------------
---------------------------------

package com.core.pageobject;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class BlogPage {


    private final By inputBox=By.name("txtbox1");
    private final By submitBtn=By.name("btnsub");
    private final String googleLink="Google";
//    private final WebElement inputBox;
//    private final WebElement submitBtn;
//    private final WebElement googleLink;

    private final WebDriver driver;
   
    public BlogPage(WebDriver driver) {
        this.driver = driver; 

//      this.inputBox = driver.findElement(By.name("txtbox1"));
//      this.googleLink = driver.findElement(By.linkText("Google"));
//      this.submitBtn = driver.findElement(By.name("btnsub"));

    }
   

     
     /**********************************
     * This Method Return  BlogPage Object
     * Because After Submit It's Stay On The 

     * Same Page     
     **********************************/
    public BlogPage submitForm(String inputTxt){
        driver.findElement(inputBox).sendKeys(inputTxt);
        driver.findElement(submitBtn).click();
//        inputBox.sendKeys(inputTxt);
//        submitBtn.click();

    return new BlogPage(driver);
    }    


     /**********************************
     * This Method Return GoolePage Object
     * Because After Click On This Link

     * It's Redirect To The Google Page
     **********************************/

     public GooglePage clickonGoogleLink(){
        driver.findElement(By.linkText(googleLink)).click();
//         googleLink.click();
      return new GooglePage(driver);
    }
}

 

Google Test Page
-------------------------------
-------------------------------

package com.core.pageobject;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
 

public class GooglePage { 
    private final By searchBox=By.name("q");
//    private final WebElement searchBox;

    private final WebDriver driver;

    public GooglePage(WebDriver driver) {
        this.driver = driver; 

//      this.searchBox=driver.findElement(By.name("q"));
    }

     /**********************************
     * This Method Return Goole Page Object
     * Because After Click On Search Button

     * Redirect To The Google Page
     **********************************/

    public GooglePage searchTxt(String searchTxt){
      driver.findElement(searchBox).sendKeys(searchTxt); 
//      searchBox.sendKeys(searchTxt);
    return new GooglePage(driver);
    }
}

 


Page Object Model Test
--------------------------------------
--------------------------------------

package com.core.pageobject;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class PageObjectModelTest {
    WebDriver driver;


     /**********************************
     *Initialize Driver For All Test
     ***********************************/

    @BeforeTest
    public void testSetUp(){
        FirefoxBinary bin=new FirefoxBinary(new File("G:\\Program Files\\Mozilla Firefox\\firefox.exe"));
        FirefoxProfile prof=new FirefoxProfile();
        driver=new FirefoxDriver(bin, prof);
    }


     /**********************************
     * This Is Created To Go the Base Page 

     * Before Every Test
     **********************************/
    @BeforeMethod
    public void testMethodSetUp(){
    driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
    }



    @Test()
    public void testSubmit() throws Exception{
        BlogPage blog=new BlogPage(driver);
        blog.submitForm("Test");
    } 



    @Test
     public void testGoogleLink()throws Exception{
        BlogPage blog=new BlogPage(driver);
        blog.clickonGoogleLink().searchTxt("Test");
    } 


     /**********************************
     * This  Is Created To Close The Driver

     **********************************/
    @AfterTest
    public void tearDown(){
    driver.quit();
    }
}