How to do Data Driven Testing using Selenium 2 (WebDriver)?

Many of us would be wondering if data driven testing is possible using Selenium 2 (WebDriver). The answer is yes, it can be done and again with the help of testNG. Below is a simple example where I’m passing data to the google search box using a 2×2 table.

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.File;
import jxl.*;

@SuppressWarnings("unused")
public class FirstTestusingWebDriver {
private WebDriver driver;
private String baseUrl="http://www.google.co.in";
private StringBuffer verificationErrors = new StringBuffer();
@BeforeClass
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@DataProvider(name="DP")
Object[][] createData(){
Object[][] testData = {{"Cheese", "Sudeep"}};
System.out.println("Data is getting created");
return testData;
}

@Test(dataProvider = "DP")
public void testUntitled(String str1, String str2) throws Exception {
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys(str1);
driver.findElement(By.name("btnG")).click();
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys(str2);
driver.findElement(By.name("btnG")).click();
}

@AfterClass
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}

If you are following the hybrid framework explained in earlier post, the same thing can be replicated with Selenium 2 also, of course with some changes in the code. Why do that? Because it’s the selenium version that’s going to be supported in future, has better ajax handling, emulates the test as a normal user would interact with the browser. And more over as per the selenium developers, the Selenium 1 is now deprecated and will be supported as maintenance only. 🙂

Advertisements

How to Handle Window based Pop up using Selenium and AutoIT?

Some times while doing testing with selenium, we get stuck by some interruptions like a window based pop up.  I have faced similar situation while doing my analysis. Since we were using a proxy to connect to internet, any page we open will ask for proxy authentication in a window based pop up. But selenium fails to handle this as it has support for only web based application. To overcome this problem we need to use AutoIT along with selenium script. AutoIT is a third party tool to handle window based applications. The scripting language used is VBScript.

So let’s take the example of the problem I was facing. Every time you open a page you get a pop up asking for authentication. To overcome the problem let create an AutoIT script first. To do so let’s create one file with any name and .au3 extension in any location. Let’s say the file name is Authentication.au3 and it’s created in the example folder of the AutoIT installation folder. So we need to know the window title of the window that is disturbing our test. Taking an example of Firefox let’s consider the window title as “Authentication Required”. The script to handle this pop up is as below which is written inside Authentication.au3. You need to write click on the file and click edit and write the following.

WinWaitActive("Authentication Required","","10")
 If WinExists("Authentication Required") Then
 Send("userid{TAB}")
 Send("password{Enter}")
 EndIf

Now save the file and click on tools and compile it. One more file with same name but with .exe extension will be created in the same location. This file needs to be used inside selenium script. How to use it. It’s pretty simple. We need to add one statement in the setUp method before calling the recursive setUp method with the URL. Below is the statement that needs to be added.

Runtime.getRuntime().exec("C:\\Program Files\\AutoIt3\\Examples\\authenticationFF.exe");

The whole path along with the file name has to be passed to exec method. Now when you fire your script your autoIT script will be fired first and the initial pop up will be handled.

Setting up Eclipse for Selenium RC

Here, we’ll discuss how to set up and configure Eclipse to use it for the java version of selenium RC. So prior to set up, let’s make sure we have all the required components gathered with us and the latest version of java installed in our system. The components required are as below.

  1. Latest version of Eclipse: This can be downloaded from http://www.eclipse.org/downloads/
  2. Selenium RC components: The version for selenium RC is 1.0.3 which can be downloaded from http://code.google.com/p/selenium/downloads/list?can=1&q=&colspec=Filename+Summary+Uploaded+ReleaseDate+Size+DownloadCount and the file name is selenium-remote-control-1.0.3.zip.
  3. Latest version of junit: This is available at https://github.com/KentBeck/junit/downloads

With these components in place we are all set to configure eclipse to do scripting using selenium RC. The following steps are to be followed for configuring eclipse.

Step 1: Extract Eclipse

Extract the content of eclipse package to your preferred location. Let’s assume here, that the contents are being extracted to C drive of your computer. Since eclipse is a fully fledged package, we need not worry about installing the same. Just extraction is sufficient. Now let’s launch eclipse by double clicking the eclipse icon inside the eclipse folder.

Step 2: Create workspace

After launching eclipse, a prompt appears to use a workspace. A custom workspace can be created using the browse button and creating a new folder. Name that new folder for convenience and select the same and click OK. Now you will be navigated to the home screen of Eclipse. There, we need to click on workbench which will take us to the work area.

Step 3: Create the project and project specific folders

Once we are in the work area, we need to create a project which will contain our scripts. To do so, click on File – New – Java Project as shown in the image below.

Once you click on the Java Project, a pop up window appears to set the parameters of your project.

Provide the name of the project in Project Name field and make sure it uses the latest execution environment. Click on Finish button and the project is created. Once the Project is created you will see it in package explorer on the left side. By expanding the project the there will be one default “src” folder created and it will have the JRE system library files associated to the project. We need to create one additional folder inside the project to hold the library files for our convenience. To do that, right click on the project folder in the package explorer and click on New – Folder.

It will open a pop up window where we need to specify the folder name. Let’s call the folder as “lib”. Once the lib folder is created, navigate to the physical location of the folder. Remember where you had created the Workspace in Step 2. Navigate to that folder, and the project folder can be located there. Once you are inside the lib folder place the library files inside it. What all library files to place? They are as follows:

  1. selenium-java-client-driver.jar
  2. selenium-server.jar (The Java Version)
  3. junit-4.8.2.jar

Now go to eclipse again and hit refresh on the lib folder by clicking the folder and pressing F5 key. You will now be able to see the library file.

Step 4: Configuring the Build Path

To use the library files placed inside the lib folder they need to be added to the build path of the project. How to add them? Right click on the lib folder in package explorer and select Configure Build Path from Build Path.

Once you click the same one pop up window comes up as shown below.

In this pop up window click on Libraries tab and click on the Add JARs button. Now navigate to the lib folder inside your project and select all the JAR files and add them.

Once you add them, click on OK. Now the build path is configured and the project is ready to be used.

Your final package explorer should look as below.

Now to do your scripting you will need to create one class file by right clicking the src folder and do the coding.

NB: there are few more steps to be followed when we are going to use testing and data driven approach which will be covered in later posts.

Setting Up Selenium IDE with Firefox

How do we set up selenium IDE? Before doing anything first we need to check if we have Firefox installed in our system. As we all know IDE is the integrated development environment, selenium provides to record, customize and run different test in Firefox. Since it’s a Firefox add-on, we need to have Firefox installed in our machines to use the same. The max version of Firefox currently supported by IDE is Firefox 5.0 and the current version of IDE is 1.0.12. So first we need to install Firefox in our machine which is available for all sorts of premier operating systems used worldwide and can be downloaded from http://www.mozilla.com/en-US/firefox/new/ for free.

Next we need to get the Selenium IDE from selenium website which is http://seleniumhq.org/download/. It will get downloaded as a .xpi file.

To install the same first open Firefox. The next thing we need to do is drag and drop the selenium-ide.xpi file to the open Firefox browser. After installation we need to restart Firefox to use the same. This cover the environment set up for the use of Selenium IDE.

Now the next question would from where do I launch the Selenium IDE. It’s quite simple. For Firefox 4 and up, click on the Firefox drop-down on top left corner and u can launch the IDE from the developer menu there. For any other Firefox with a version below 4, the IDE can be launched from Tools menu at the top. Now you are ready to use the IDE.

Selenium 2.0 Released….

It’s been quite some time since my last post. I’m really excited about Selenium 2.0 which was released yesterday. Have a lot of research to do on it. How to data drive test using 2.0 and quite a few stuff. Till then, I’ll post selenium teachings step by step so that everyone can benefit. 🙂

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 :).

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 🙂