Monday, September 24, 2012

Selenium RC using Java Post 6 of 10


Wrapping in Selenium

 



You can wrap frequently used selenium calls with functions or class methods of your own design. 

For example, many tests will frequently click on a page element and wait for page to load multiple times within a test.  Using this you can remove your duplicate codes as well as you can save time.

 

I create a new class under the …..test.util package.  I name my class as SeleniumUtil.java

Now I need to create a method for Click and Wait. In my tests sometimes I need to click a locator and wait for some time until something happens ( Eg- Until it changes values in another  dropdown)

 

Following is my SeleniumUtil class and mehod created





package com.ABC.test.util;

 

import com.thoughtworks.selenium.Selenium;

 

public class SeleniumUtil {

Selenium Sel;

 

public SeleniumUtil(Selenium sel){

     

      Sel = sel;

}

 

public void ClickAndWait(String locator, String timeOut)   

Sel.click(locator);

      Thread.sleep(Long.parseLong(timeOut));

      
}


}






Here I pass the locator and timeout as a parameter. In the body you can see that I click the locator and wait for some time.

 

 

Now whenever I have to use Click and wait I can use this method in my tests.

 

Now I use this in one of my other classes (Activity Class )


public class Activity {

public Selenium SEL;   

public SeleniumUtil sUtil;

     

      public Activity(Selenium Sel){

           

            SEL = Sel;

            sUtil = new SeleniumUtil(Sel);

           

      } 

      public void gotoSetupPage(String timeOut){           

            SEL.click("css=div.ajax__dropdown_arrow.ajax__dropdown_arrow_image");

            sUtil.ClickAndWait("link=Super Admin Menu", timeOut);

            sUtil.ClickAndWait("link=Setup", timeOut);

 

 

}

}

Wednesday, September 19, 2012

Selenium RC using Java Post 5 of 10

UI mapping and Page Objects

Today I’am going to tell you about UI mapping and Page Objects.
In your project create a Folder and names it as Resources
Now New à File -> and under the Resources folder create a new file and name it as locator.properties
Now in my locator file I need to create all control id’s of Login page. Here I’ll take username txt box , password txtbox and Login button
I can take it from my Login class

ABC.login.txtUserName=id=body_UserNameTextBox

ABC.login.txtPassword=id=body_PasswordTextBox

ABC.login.btnLogin=id=body_LogOnButton

Now we need to have a method for find the locator file and get the details from the file
In my Test Base class I creates 2 variables


public static String LocatorPrpertyPath = "D:\\worksplace\\Traning\\Resources\\locator.properties";

public static HashMap Locator = new HashMap();


Now in my method I am going to get the locator file and get the details of property file in to a Hash Map

@BeforeClass

public void getLocatorDetails() {

      Properties pro = new Properties();

      try {

 

            FileInputStream in = new FileInputStream(LocatorPrpertyPath);

            pro.load(in);

            Enumeration em = pro.keys();

            while (em.hasMoreElements()) {

                  String str = (String) em.nextElement();

                  Locator.put(str, (String) pro.get(str));

            }

      } catch (IOException e) {

            System.out.println(e.getMessage());

      }

}

This is also a Beforeclass method

Now I should change my code in Login class to get the control id’s from property file (actually from the hashmap )

public class Login {

 

      public Selenium SEL;

      public static String ptimeout;

      public static HashMap Locator;

     

      public Login(Selenium Sel, String PtimeOut, HashMaplocator){

           
            SEL = Sel;

            ptimeout = PtimeOut;

            Locator = locator;

      }

      public void login(String uname,String pword){

           

                SEL.windowMaximize();

                SEL.open("http://localhost:8080/LogOn.aspx");

              SEL.type(Locator.get("ABC.login.txtUserName"),uname);

              SEL.type(Locator.get("ABC.login.txtPassword"), pword);

              SEl.click(Locator.get("ABC.login.btnLogin"));

              SEL.waitForPageToLoad(ptimeout);

      }

}

This is the new login class. Now I am getting the login page controls from the locator.properties file and for this I used the filereading and hash map.
Now I have to change the login object initiation method since new variable is added to the the constructor.

Test Base class

public class TestBase {

     

      public Selenium Sel;

      public Login login;

      public static String SystemtimeOut;

      public static String LocatorPrpertyPath = "D:\\worksplace\\Traning\\Resources\\locator.properties";

      public static HashMap Locator = new HashMap();

 

@BeforeClass

public void InitSelenium(){

      Sel = new DefaultSelenium("localhost", 4444, "*firefox", "http://localhost:8080/LogOn.aspx");

      Sel.start();

      }

 

@BeforeClass

@Parameters({"pageTimeOut"})

public void setUp(String systemtimeout){

      SystemtimeOut = systemtimeout;

}

 

@BeforeClass(dependsOnMethods = { "setUp","InitSelenium" })

public void initPageObject(){

     

      login = new Login(Sel, SystemtimeOut, Locator);

     

}

@BeforeClass

public void getLocatorDetails() {

      Properties pro = new Properties();

      try {

 

            FileInputStream in = new FileInputStream(LocatorPrpertyPath);

            pro.load(in);

            Enumeration em = pro.keys();

            while (em.hasMoreElements()) {

                  String str = (String) em.nextElement();

                  Locator.put(str, (String) pro.get(str));

            }

      } catch (IOException e) {

            System.out.println(e.getMessage());

      }

 

Now you can see that login object has 3 parameters now. (Locator Hash map in the new one)
So using Page objects you can improve the maintainability of the Test automation project. If new control added or existing control changes you can handle it using property file.

Tuesday, September 18, 2012

Selenium RC Using Java Post 4 of 10

Now I am going to talk about concept of page object. This is an extremely useful design pattern for UI tests as it abstracts away how we get to different pages or screens. Page Object design helps us create a DSL for our tests that if something were to change on the page we don't need to change the test, we just need to update the object that represents the page

Now I’m going to create a new class which is to place my all the functional methods related to Login

Page. Before that I create a new package which I am going to label as com.ABC.Test.Functional under this package I creates the class Login

public class Login {

public Selenium Sel;

public static String ptimeout;

public Login(Selenium Sel, String PtimeOut){

Sel = new DefaultSelenium("localhost", 4444, "*firefox", "http://localhost:8080/LogOn.aspx");

ptimeout = PtimeOut;

}

public void login(String uname,String pword){

Sel.windowMaximize();

Sel.open("http://localhost:8080/LogOn.aspx");

Sel.type("id=body_UserNameTextBox",uname);

Sel.type("id=body_PasswordTextBox", pword);

Sel.click("id=body_LogOnButton");

Sel.waitForPageToLoad(ptimeout);

}

}

Now I create the Selenium instance and login method and included all of login steps here. So I removed my Login steps from the testSucessLogin method.

Now I’m going back to TestBase class and create new method initPageObject()

Within this method I am going to create new object of Login class. (All the page objects will be initialize here )

public void initPageObject(){

login = new Login(Sel, SystemtimeOut);

}

I creates a new method “setup “ which is going to list all the setup variables . Here I am going to setup the “systemtimeout” I define this as a @Beforeclass and do the parameterization using TestNG xml.

@BeforeClass

@Parameters({"pageTimeOut"})

public void setUp(String systemtimeout){

SystemtimeOut = systemtimeout;

}

Now in my PageObject method I might get a problem because before create the objects I need to run the initSelenium and Setup method. For this I use TestNG annotation - @BeforeClass(dependsOnMethods = { <method names})

@BeforeClass(dependsOnMethods = { "setUp","InitSelenium" })

public void initPageObject(){

login = new Login(Sel, SystemtimeOut);

}

Now I need to call my login method under my testSucessLogin Test method

login.login(uname, pword);

Monday, September 10, 2012

Selenium RC using Java Post 3 of 10

HTML Editor Sample Page

 

Selenium RC with java Post 3 of 10

In this post I’ll discuss about How to handle drop downs, Text fields ,Date pickers,  Data Grids and Paging using Selenium.

 

How to get the and set values from Text fields

 

Sel.type("id=body_body_shortNameTextBox", "manu11");

Get value from Text box

Sel.getValue("id=body_body_shortNameTextBox");

 

How to get and set values from Drop down

Can select values from 3 methods

From name of the item , ID and Index

Sel.select("body_body_countryDropDownList", "label=Singapore");

Sel.select("body_body_countryDropDownList", "ld=10");

Sel.select("body_body_countryDropDownList", "lndex=118");

 

 

Get the selected value in drop down

Sel.getSelectedLabel("body_body_countryDropDownList");

 

Sel.getSelectedId("body_body_countryDropDownList");

 

Sel.getSelectedIndex("body_body_countryDropDownList");

 

 

Data Grids

 

Following is my datagrid

Now I need to read the data grid (which has paging ) and then Click the edit button on particular row which I need to edit.

 

Now things I need to consider are

Unique name and it’s column id  which I can read the datagrid

Control name of the icon which I need to click to go to the edit page

No of paging which I need to traverse through to find the name (or element ) which I am search for

 

Now to start up I find the column name of the field I am looking for  -  it’s column 2  (I can find the column index using selenium IDE ) here it’s 1.

Element which I need to click is Body_body_activityGridView_selectImageButton (plus it has a unique id at the end and it’s increments with each row )

 

If I create a script to find the given name’s row  and click the edit image as follows

for(int row=1;row<11;row++){       

        activityName = Sel.getTable("//table[@id='body_body_activityGridView']/tbody."+ row +".1");      

       if (activityName.equals("ManujayaAutomation")) {

                  

                   Sel.click("id=body_body_activityGridView_selectImageButton_" + (row-1));

                   Sel.waitForPageToLoad("30000");

                   break;

       }

  

From this method I can find the find my activity name

Sel.getTable("//table[@id='body_body_activityGridView']/tbody."+ row +".1");

 

For getTable mehod I am passing the table id, row id and column id .

Now if my acivity name is in another page of this grid then I should handle the paging as well .

String noOfPagSentence = Sel.getText("css=span.gridPagerInfo");

    int length = noOfPagSentence.length();

    noOfPagSentence = noOfPagSentence.substring(noOfPagSentence.indexOf("of ")+3, length);

    int noOfPage = Integer.parseInt(noOfPagSentence);

    String activityName="";   

    int paging;   

    for(paging=1; paging<(noOfPage+1); paging++){

                if (activityName.equals("ManujayaAutomation")){                     

                                break;

                }

               

                if (paging>1){                             

                                  Sel.click("link=" + paging);

                                  Sel.waitForPageToLoad("30000");

                }               

        for(int row=1;row<11;row++){      

                                activityName = Sel.getTable("//table[@id='body_body_activityGridView']/tbody."+ row +".1");

                 if (activityName.equals("YoosufAutomation")) {

                                Sel.click("id=body_body_activityGridView_selectImageButton_" + (row-1));

                                 Sel.waitForPageToLoad("30000");

                                  break;

                  }

        }

        if (paging == noOfPage+1){

                break;

        }

From the first 4 lines I am finding the no of pages which has in this grid

Using the first for loop I am handling the paging related things , I am traverse through each page in the grid until I find the wanted element.

 

 


HTML Code

Sunday, September 9, 2012

Selenium RC using Java Post 2 of 10

HTML Editor Sample Page

  

Run the Tests using TestNG Xml

You create a XML file and call the Test Suite to run using TestNG
Create a XML file --   New >>other >> XML >> XML file
In your xml file if you need to run the test suite you can  define it like this
<suite name="ABC_Testing" verbose="1" parallel="false" thread-count="1">
</suite>

If you want to provide a Test name which displays with your results then XML will look like this
<suite name="ABC_Testing" verbose="1" parallel="false" thread-count="1">
<test name="ABC Testing" thread-count="1">
</test>
</suite>

Now if you need to just run a one test class and methods allocated to that then your file should look like this
<suite name="ABC_Testing" verbose="1" parallel="false" thread-count="1">
<test name="ABC_Testing" thread-count="1">
<classes>
  <class name = "com.ABC.test.scripts.TestLogin">
   <methods>
            <include name="sucessLogin" />
         </methods>
  </class>
 </classes>
 </test>
</suite>
Now if you need to pass the data through your XML then you can parameterized your tests and then pass the data to your parameters using xml file
Now first you need to change your test to accept parameters.
@Test
                @Parameters({"userName","password"})
                public void testSucessLogin(String uname , String pword) {                    
        Sel.windowMaximize();
        Sel.open("http://ABC:8080/LogOn.aspx");
        Sel.type("id=body_UserNameTextBox",uname);
        Sel.type("id=body_PasswordTextBox", pword);
        Sel.click("id=body_LogOnButton");
        Sel.waitForPageToLoad("30000");cc
Now you need to define the parameters in the xml file and assign the values to them

<parameter name ="userName" value ="abc.admin@ABC.com"/>
<parameter name ="password" value ="Qwer1234"/>

Now the run the xml and see ………….



Thursday, September 6, 2012

Selenium RC Using Java - Post 1 of 10


HI All

I thought I should start a Selenium  blog posts series. In this series I will try to cover selenium related beginning thins to Advance features.  In this series I’ll do it using Java and I have listed the pre-requisites

to start up. Hope to cover whole series within 2 months. After that I’ll think of doing a series of selenium using C# and MStest.

Pre Conditions
Install Eclipse
Download TestNG latest jar  file
Download Selenium server latest jar file
Install Selenium IDE

Creating the Project in Eclips
Create New Java Project

















Create a new package for testscripts
 













Now in your source folder create a new folder name Lib

Then place your Selenium Standalone server executable jar file in to the Lib folder

And place your TEstNG executable jar file in to the same place

Eg - selenium-server-standalone-2.20.0

        testng-6.3.1

 
Go back to the project

Build path -- > Configure Build path

In Libraries tab add the External Jars (which are in the Lib folder)

 

Now go to the testscripts package and add new Class (main)

 




Now in your main class , Create code to start the Selenium Server

Selenium Sel = new DefaultSelenium("localhost", 4444, "*firefox", "http://localhost:8080/LogOn.aspx" );

Sel.start();
Start the Selenium Server by type this command   -  java –jar Selenium Standalone 2.20.0jar
 

Run the project and verify weather selenium browser start or not

Now we’ll start our test script

If you don’t have Selenium ID installed then open a firefox browser and get installed.

If it’s already installed then you can start the IDE by Tools à Selenium IDE

Once you start the IDE now type the URL in your browser

In my App it’s Http://ABC.Logon.aspx

In this scenario it’s navigating to a Login page

First I type Username , then password and Then Submit button .

All of my Actions will record in the Selenium IDE


 

















Now when you select each action you can find the command , target object and the values

 



 













Now you can create your script according to this

Following is my script for the Login

 
      Sel.open("http://ABC:8080/LogOn.aspx");

        Sel.type("id=body_UserNameTextBox","abc.admin@abc.com");

        Sel.type("id=body_PasswordTextBox", "Qwer1234");

        Sel.click("id=body_LogOnButton");

        Sel.waitForPageToLoad("30000");

 
Additionaly I have put a waitforpageload command because I need to wait until my page loads after I click logon button

Now run this file … it should  run

Now we need to make use of the TestNG which is a testing framework. We can make automation test cases now

Earlier we have mapped  TestNG jar file to the project

Now I can use @Test annotation to make my test case.

Then I can use methods instead of the main method, (no need of main method now )

Now I rename my main methof to testSucessLogin()

               

@Test

                public void testSucessLogin() {

        Sel.windowMaximize();

        Sel.open("http://localhost:8080/LogOn.aspx");

        Sel.type("id=body_UserNameTextBox","abc.admin@ABC.com");

        Sel.type("id=body_PasswordTextBox", "Qwer1234");

        Sel.click("id=body_LogOnButton");

        Sel.waitForPageToLoad("30000");

       
                }

Now I can create another method to verify the invalid login

public void testInvalidLogin() {

        Sel.windowMaximize();

        Sel.open("http://localhost:8080/LogOn.aspx");

        Sel.type("id=body_UserNameTextBox","abc.admin@ABC.com");

        Sel.type("id=body_PasswordTextBox", "Qwer12");

        Sel.click("id=body_LogOnButton");

        Sel.waitForPageToLoad("30000");

}

 
When I enter an invalid password system will give me an errormsg , so I need to catch it and verify it

Selec t and right click on error msg and then select the command verify textid

Now in Selenium IDE it display as this


 

 

You can write this assert as this - 





Assert.assertEquals(

Sel.getText("id=ErrorDetailLabel"), "Incorrect user name or password!");

 
Make sure you get the TestNG Assert when you selecting Assert from the list. (Becuase junit assert is  also there )

 





Now my Test method looks like this

@Test

               
public void testInvalidLogin() {
Selenium Sel = new DefaultSelenium("localhost", 4444, "*firefox", "http://localhost:8080/LogOn.aspx");

        Sel.start();

        Sel.windowMaximize();

        Sel.open("http://localhost:8080/LogOn.aspx");

        Sel.type("id=body_UserNameTextBox","abc.admin@ABC.com");

        Sel.type("id=body_PasswordTextBox", "Qwer12");

        Sel.click("id=body_LogOnButton");

        Sel.waitForPageToLoad("30000");

       Assert.assertEquals(Sel.getText("id=ErrorDetailLabel"), "Incorrect user name or password!");
   

                }

 

Now I am going to create a Test Base class. Concept of testbase class is to initialize my variables , create new objects and so

Create a new package -  Com.ABC.test.Util

Under that package create new Class   -  TestBase

In  this class create the Selenium new Object

public class TestBase {

                public Selenium Sel = new DefaultSelenium("localhost", 4444, "*firefox", "http://localhost:8080/LogOn.aspx");

}

Now you don’t need to create Selenium objects each time you create a tests.

Go to the TestLogin class and Extend the TestBase class

-    public class TestLogin extends TestBase

Now if you need to Start the selenium for this class you can create a constructor and start the selenium

//Constructor

public TestLogin(){

               

                Sel.start();

}

Now you can Run and check your tests :)
In my Next post i'll explain about TestNG XML and How you run your tests using TestNG xml .....