Hybrid Testing (Data + Keyword Driven) using Selenium

Today, we’ll see how to do hybrid testing using selenium. Let’s discuss what’s hybrid testing first. Hybrid testing is a combination of Data Driven testing along with keyword. Here we’ll use some keywords as the driving parameters in data driven testing the data sheet. The keywords will be defined by the user, and let’s call them user defined keywords.

Before getting into the framework, let’s discuss on what are the external files which will be required. The list of files that will be required in addition to selenium client driver and selenium server jar files are as below

  1. TestNG: in order to data drive our test, we would require the latest version of testNG jar file which is now testng-5.14.1.jar and can be downloaded from http://testng.org/doc/download.html
  2. JXL: in order to use Microsoft Excel files as data source we would need the jxl jar file which can be downloaded from http://sourceforge.net/projects/jexcelapi/files/
  3. Latest Junit: this will be required to verify certain condition and can be downloaded from https://github.com/KentBeck/junit/downloads
  4. TestNG plugin for Eclipse: This will be required to run the TestNG scripts in eclipse and the content of this plugin has to be placed inside the “dropin” folder inside the eclipse directory. The file can be downloaded from http://testng.org/doc/download.html

The first 3 file need to be added to the build path in the project in eclipse to use them. The fourth file needs to extracted in the dropin folder of the eclipse folder so that when you open the droping folder, a plugin folder is created inside it. This is all about configuration that is required for such testing.

Now let’s start with how to test using this framework. Let’s test the IBN Live website, where we’ll use the keyword ‘link’ to drive our test. So to do this, we need to place this keyword ‘link’ in the data sheet. This will decide the action when the ‘link’ keyword is passed to the program. The corresponding cell values for that particular row will be used for different operations on the same. Below is the data sheet that we are going to use.

testData property xPath value expectedResult permission name
pagetitle CNN-IBN, Live India News,Top Breaking News,World,India,Business,Sports, Entertainment & Health News
link link=News click News
link link=Politics click Politics
link link=Movies click Movies
testData

Here using selenium, we are going to test the page title of the landing page and use the link property to navigate to different pages. So first let me explain the data table. “testData” is the table marker which will tell the start and end point of the table. The column headers will be used as variables. Here property defines the property on which we are going to perform certain actions. xPath will be used to locate the properties, value will be used to enter some data or select any object, expected result will be used to compare the actual value to the expected value, permission will determine the course of action and name will be used to give meaningful name while generating result. Below is the sample code that will drive our Hybrid test.

import com.thoughtworks.selenium.*;
import org.junit.AfterClass;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import java.io.File;
import jxl.*;

public class DataDrivenTest extends SeleneseTestCase{

    @BeforeClass
    public void setUp() throws Exception {
        setUp("http://ibnlive.in.com/", "*iexplore");
        selenium.open("/");
        selenium.setTimeout("60000");
        selenium.waitForPageToLoad("60000");
        selenium.windowMaximize();
        selenium.windowFocus();
    }

    @DataProvider(name = "DP")
    public Object[][] createData() throws Exception{
        Object[][] retObjArr=getTableArray("D:\\Work\\Data Driven Testing\\Data Driven Test\\Resources\\Data Sheet.xls",
                "Data", "testData");
        return(retObjArr);
    }

    @Test (dataProvider = "DP")
    public void testElements(String property, String xPath, String value, String expectedResult, String permission,
 String name) throws Exception {
        if(property.equals("pagetitle")){
        	if(selenium.getTitle().equals(expectedResult)){
        		System.out.println("The page title is displaying properly");
        	}
        	else
        		System.out.println("The page title is not correct");
        }
        if(property.equals("link")){
        	if(selenium.isElementPresent(xPath))
        		System.out.println("The link "+name+" is present");
        	else
        		System.out.println("The link "+name+" is not present");
        	if(permission.equals("click"))
        	{
        		selenium.click(xPath);
        		selenium.waitForPageToLoad("60000");
        	}
        }
    }

    @AfterClass
    public void tearDown(){
        selenium.close();
        selenium.stop();
    }

    public String[][] getTableArray(String xlFilePath, String sheetName, String tableName) throws Exception{
        String[][] tabArray=null;

            Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
            Sheet sheet = workbook.getSheet(sheetName);
            int startRow,startCol, endRow, endCol,ci,cj;
            Cell tableStart=sheet.findCell(tableName);
            startRow=tableStart.getRow();
            startCol=tableStart.getColumn();

            Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000,  false);

            endRow=tableEnd.getRow();
            endCol=tableEnd.getColumn();
            System.out.println("startRow="+startRow+", endRow="+endRow+", " +
                    "startCol="+startCol+", endCol="+endCol);
            tabArray=new String[endRow-startRow-1][endCol-startCol-1];
            ci=0;

            for (int i=startRow+1;i<endRow;i++,ci++){
                cj=0;
                for (int j=startCol+1;j<endCol;j++,cj++){
                    tabArray[ci][cj]=sheet.getCell(j,i).getContents();
                }
            }

        return(tabArray);
    }

}//end of class

The createData method will create a virtual copy of the data sheet in memory. Inside it, we need to specify the data sheet path along with its name, the sheet name, the table marker that we discussed earlier. Here, the testElements method is driving the test depending on the input, it’s getting from the excel sheet. It can be customized to accommodate more types of properties like drop down, text box, text area, etc. according to user needs.

This is a way how we can data drive our test. I hope that I made some people happy with this post. Please leave a reply in case of doubts :).

Advertisements

How to take full page screenshots in browsers other than Firefox using Selenium?

Here is a problem which very few people would face. The situation is you need to have a full page screenshot of whatever page you visit while testing a web application and you are not allowed to use any third party tool for the same for any reason (e.g security purposes).

There is no predefined method to take full page screenshots using selenium for browsers other than Firefox. The solution for this is a work around code that will give page downs and take screenshots after each page down. Again we cannot determine the number of page downs required for a particular page as scroll length cannot be retrieved using java. So the number of page downs is solely dependent on the user. Then again we can take one element which appears at the bottom of the page across all the pages in the application. The last screen capture can be used by focusing on this particular element so that the bottom of the page is always captured. Below is the work around code to achieve this particular objective.

public void screenCaptureOB() throws Exception{
Robot robot = new Robot();
String screenName = new String();
screenName = "D:\\Regression\\Data Driven Regression\\test-output\\screenshots\\screenshot"+i+".png";
selenium.windowFocus();
selenium.captureScreenshot(screenName);
i++;
robot.keyPress(34);
screenName = "D:\\Regression\\Data Driven Regression\\test-output\\screenshots\\screenshot"+i+".png";
selenium.captureScreenshot(screenName);
i++;
robot.keyPress(34);
screenName = "D:\\Regression\\Data Driven Regression\\test-output\\screenshots\\screenshot"+i+".png";
selenium.captureScreenshot(screenName);
i++;
robot.keyPress(34);
screenName = "D:\\Regression\\Data Driven Regression\\test-output\\screenshots\\screenshot"+i+".png";
selenium.captureScreenshot(screenName);
i++;
robot.keyPress(34);
screenName = "D:\\Regression\\Data Driven Regression\\test-output\\screenshots\\screenshot"+i+".png";
selenium.captureScreenshot(screenName);
i++;
screenName = "D:\\Regression\\Data Driven Regression\\test-output\\screenshots\\screenshot"+i+".png";
selenium.focus("Last element of the page");
selenium.captureScreenshot(screenName);
i++;
}

 To use this method, we need to import the java.awt.Robot class. Please leave a comment if you need any clarification.

How to run Firefox 4.0 and higher versions using Selenium RC?

I have been facing this problem for a quite long time. I was unable to run test using selenium RC 1.0.x. The problem behind this is: in the selenium server tha max version of firefox to be used is defined as 3.6. To overcome this problem, we need to override the value to the version number you want to use (in my case 4.0). Below are the step on how to do it:

  1. Change the file extension of the selenium-server.jar file to .zip.
  2. Now, extract the file content to any particular folder let’s say ‘selserver’.
  3. Now search for all available install.rdf files. You may get 5-6 such file depending on the version.
  4. Open those files with note pad. In this file you will see a tag like “<em:maxVersion>3.6.*</em:maxVersion>”. As it’s defined as 3.6, hence we need to change it to 4.0 and save the file.
  5. Compress all the files again as you had decompressed them to selenium-server.zip. Change the file extension to .jar.
We are ready with our server with support for Firefox 4.0. Now happy testing using Firefox 4.0 :).

How to get any attribute if no default method is defined for the same?

While analyzing selenium, I got a problem of retrieving a particular property as no default method was defined for retrieving the same in the Selenium API. The solution for the same was a little tricky. Let me explain the same with an expample.

Example: Suppose in a page there is a link called “your link”. When hover your mouse over that particular link, a title tag is displayed saying “This link opens in new window”. Now the problem is you will have to test is the text of the title tag is correct or not. To do the same, we need to retrive the title tag of the link using locator for the link, let’s say we’ll take the xPath of the link. But there is no default method to retrieve the title tag in Selenium API. To get this title tag now, we’ll have to use the getAttribute() method. The method to get it is as below.

Let’s say the xPath of the link is: link=your link
To get the title tag the xPath needs to be appended with the attribute with ‘@’ at the end.
So, the new xPath becomes: link=your link@title
Let’s say, a local variable xpath has this xPath value. So, when we call selenium.getAttribute(xpath) now, it will return the text which the title attribute of link contains, in this case “This link opens in new window”.

Similarly another such example would be to get the alt property of an image in a page.

How to Start IE 8 using Selenium RC in Win Vista or Win 7?

While using Selenium RC, this is a common experience that when the server is started in normal command prompt in Win Vista or Win 7, then IE fails to open the URL. A temporary file location is entered in the browser which leads to the failure of the first step of a test i.e opening the browser and entering the URL. The solution to this problem is quite simple. The command prompt needs to be started as Administrator. The process to do so is simple. In accessories, right click the ‘command prompt’ and choose ‘Run As Administrator’ and then start the selenium RC server. This will solve the Internet Explorer issue in Win Vista and Win 7 machines.

There is one alternative way to solve the issue too. The issue occurs because of the security settings of the browser. So if we tweat the browser security settings a little, we’ll be able to run IE 8 using selneium. Below are the steps to be followed.

  1. Go to Tools>>Options.
  2. Click on Security tab.
  3. Uncheck the “Enable Protected Mode” check box and click on Apply and Ok.

We are good to execute in Win 7 and Vista IE 8 and above 🙂