Tuesday, July 9, 2013

Page Object Pattern using JUnit Webdriver and Java Classes

Page Object pattern at  beginner's Level is nothing but dividing Test Cases and Page Object Classes . The Page Object Class is nothing but a Class with methods ( such as doing any function on web Element , returning any other page Object etc kind of stuff ) for that page and instantiate of those objects ( using page Factory ) .
Lets take example of One of our Sample Test Class that have 2 Test in it.

package com.tests;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import com.pages.LocatorPage;
import com.pages.ContactUs;
import com.pages.Home;
import com.pages.searchResults;
public class SearchWebPage {
private Home page;
searchResults searchAgainpage;
public String url;
public WebDriver driver1;

public void opentheBrowser() throws InterruptedException
driver1 = new InternetExplorerDriver();
page = PageFactory.initElements(driver1, Home.class);
url = "any url you want to explore";

// @Test
public void userSearch() throws InterruptedException
searchAgainpage = page.searchText("AAA");

public void findFA() throws InterruptedException
ContactUs contactuspageobject = page.goToContactUsPage();
LocatorPage locatorpageobject = contactuspageobject.individualBranchLocator();

The website which i have used for writing sample codes has below fields on its Homepage

HomePage.Java should contains the following code:

package com.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Home {
protected WebDriver driver;
protected String url = null;

@FindBy(name = "query")  // This is method to find search text box location
private WebElement q_text;

@FindBy(xpath = "/html/body/center/div/div/div[2]/div/div/div/form/table/tbody/tr/td[3]/input")
private WebElement button_btng; // the xpath above is for search Button

@FindBy(css = "html body td > a[href='contact_us.html']")
private WebElement contactUs; // Contact Us link button

public Home(WebDriver d) {
this.driver = d;

public void open(String str){

public void close() {

public String getStringTitle() {
return driver.getTitle();

// search a keyword and Returns a searchResults Class Objects to Caller
// Class.

public SearchResults searchText(String search)
throws InterruptedException {
return (PageFactory.initElements(driver, SearchResults.class));

public void clickOnSearch() {

public ContactUs goToContactUsPage()
return (PageFactory.initElements(driver, ContactUs.class));


Third page is SearchResults.Java--- This page is returned when user search any text and click search on HomePage.Java Class.

public class SearchResults {

protected WebDriver driver;
@FindBy(xpath = "/html/body/div[2]/div[2]/div/a/img")
private WebElement homepage;
@FindBy(css = "html body div td.BarHeader input[type='text']")
private WebElement searchAgainText;
@FindBy(css = "html body input[type='image'][src='/img/btn_search.gif']")
private WebElement searchAgainSubmitButton;

public SearchResults(WebDriver d)
this.driver = d;
public String getTitle()
return (driver.getTitle());
public void closeBrowser()

public void takeMeHomeFromSearchAgainPage()
public void searchAgain(String search) throws InterruptedException

Now when User click on contact Us link , a contactUs page is returned to caller method.
package com.pages; -- Contact us page has mainly few links to go to Locator page. So on clicking any of the link it returns the Locator page object.


public class ContactUs {
           WebDriver driver ;
           @FindBy(css="html body a[href=''locator"]")
            private WebElement indi_investor;
            @FindBy(css="html body a[href='about/offices/locator/index.html']")
            private WebElement insti_investor;
            public ContactUs(WebDriver d)
           public LocatorPage individualBranchLocator() throws InterruptedException
           return (PageFactory.initElements(driver, LocatorPage.class) );

and last but not the least  LocatorPage - On entering Location here and entering search button , a page is returned with Title " Locator Page" , which we need to verify by using assert statements.

public class LocatorPage {
           WebDriver driver;
           @FindBy(css="html body input#zipCode")
           WebElement locationZip; // Enter ZIP CODE field on Locaror page
           @FindBy(css="html body img[src='img/btn_search.png']")
           WebElement searchbutton; // Search Button on Locator Page
           public LocatorPage(WebDriver d)
          public void findFinancialAdvisor()
           locationZip.sendKeys("10004"); //For NY 
           if (driver.getTitle().equalsIgnoreCase("Locator Page ") ) // this is comparing if on clicking search   //button the page which is coming has title "locator Page" then its expected result is equal to actual one.
            System.out.println("We have Entered correct page");
below Diagram will be helpful in understanding what is calling what. 

Sunday, June 16, 2013

Selection multiple options from Drop-down with Checkbox List

In Continuation of the Drop-down topic that i have written earlier ( Click to read) , i forget to mention one more kind of Drop-down  as given below :-

 This works as follow   , on clicking All residential Properties , a drop down will appear with multiple checkbox to select . user can select Multiple option at a time from this Checkbox list . The Concept for this is again same

Click on Main element , wait for subelement to appear on the screen and click on submenu one by one using ActionBuilder Class. Let's come to code

    Actions action = new Actions(driver);
    WebElement mainDropdownElement = driver.findElement(By.id("proptypecheck")); // main Element
    WebElement subElement1 = driver.findElement(By.id("ptypecheck_5")); // Sub Element 1
    WebElement SubElement2 = driver.findElement(By.id("ptypecheck_8")); // SubElement 2
    /* Action_one basically dealing with clicking main Element and action after that is clicking on Checkboxex one by one */   
    Action action_one = action.click(mainDropdownElement).build();
     action.click(subElement1).click(SubElement2).build().perform()    ;

Hope that Helped ....

Saturday, June 15, 2013

Selecting Multiple Option at a time from a List

One of the Scenario that is less frequent but comes in picture sometime is when we have to select
a Multiple options from a list Box  e.g. you are applying for a job and you have to select Domain in which you are working such as Finance , Retail etc . The below screen will give you an idea

So lets start the Coding for the same . This can be done very easily using the AdvancedUserInteractions
You can read a lot about them Here
We will be using some KeyBoard Actions  ( We have to hold CONTROL key and then Click on options which we want to select ) , so the same can  be done using ActionBuilders in webdriver.Lets take a look at
the sample code for the same scenario

        Actions builder = new Actions(driver);
        WebElement option1 = driver.findElement(By.id("m_opt_0"));

        WebElement option2 =driver.findElement(By.id("m_opt_3"));
        Action select_multiple = builder.build();

what the Hell above code is doing ??

1) Its saving both the Options you want to select in a webElement Object .
2) Using Actionbuilder its Pressing CONTROL Key , and then Clicking option1 object and subsequently Option2 element .

Hope that Helped.

Friday, June 14, 2013

Locating and element which is SubElement of a Dropdown and becomes visible only when Parent Element is Hovered.

This Scenario is related mainly to Webpages in which we have some dropdown Element and that element comes only when we Place our mouse on that parent Element . On placing/hovering mouse , a dropdown list is visible and we have to click on a particular link. At first , this seems quite simple  and we will start recording the same in IDE and will check if the same is recorded and can be run back. If that happened you are lucky and probably you will never visit this page or google this problem , but in other case you may land on this kind of blog ( may be  on a better one with more desription ..)

So lets start working on this ....

Remember the power of OBJECTS ( here in my case OBJECTS are just WEBELEMENTS ). below is the screen shot for one of the website that has following kind of scenarios.

Sample Website

Now we have to do 2 steps mainly
1 ) Go to parent element and wait for dropdown to be visible
2) Click on the Desired element as soon as the same is visible in dropdown

not wasting your time here , i am pasting code which i used in my case .( Remember the Titans who gave an idea about this thing to me )

                  driver.navigate().to(" ** URL HERE **");
                  WebElement mnEle; // First Element Locator .In Above case Wealth Locator
                  mnEle = driver.findElement(By.xpath("**** Write your Favorite way of Locating Element **"));
                 // Locates first Element and saves it in mnEle
                  Actions builder = new Actions(driver);
                  // The line below will find the Second Element and clicks on that Image
                  driver.findElement(By.xpath(" ** same thing again *** ")).click();

Hope that Helps ...:) :)
there are some other methods too like using JavaScriptExecutor that will search the element in Document and click on the sub element after Mousehovering first element.

Thursday, June 13, 2013

Switching from one frame to Another

One of the Classic Scenario that is faced by newbies in Selenium ( yes, i am a newbie too.. ) is that IDE locates the element when clicked and Highlighted but when Code in Java ( i love java ..u can choose any language you are good into) is ran it shows error element not found ...blah blah.

This is because there is an iframe in which your element is located and you are trying to locate that without switching the frame.

Simple Step to do this is as follow :-

WebElement i_frame = driver.findElement(By.xpath("/html/body/div/div[2]/div/div/iframe"));
// you can find the element iFrame by any other suitable method like id , css  locator etc .
driver.switchTo().frame(i_frame);  // switching is done ..now happy execution....

See below pic whichh shows presence of Iframe in HTML source code.

Handling Elements of a Webtable

The Code for Accessing a Cell value of a webtable would be like this. 

 driver.navigate().to(" Site which you want to recordl");
 WebElement table = driver.findElement(By.xpath("/html/body/div/div[4]/div/div/div[2]/div[2]/div[3]/table/tbody"));   // This would be the Xpath for locating the Element table in which tr and td exists
Collection<WebElement> table_Row_Object = table.findElements(By.tagName("tr"));
// The collection of Web Elements is collection all the WebElements with Tags tr in it. This is for table Object //only
WebElement table_Cell , table_Row ;
Collection<WebElement> tr_collection;
String Value_Cell;
 for ( Iterator<WebElement> i = table_Row_Object.iterator();i.hasNext(); )
         table_Row = i.next();  // First Weblelement of tr is assigned
         tr_collection = table_Row.findElements(By.tagName("td")); //  Find all td in tr webelement .
         for ( Iterator<WebElement> j = tr_collection.iterator(); j.hasNext();)
             table_Cell = j.next();
             Value_Cell = table_Cell.getText();
             System.out.println(Value_Cell); // And we won.... :)