Behavioural Driven Testing using Selenium and Scalatest

Hi All, wish you a very happy new year. It’s been a long time since my last post and this is the first one of 2013. I had been doing some interesting stuff over past few weeks on Behaviour Driven Automation testing and will share with a simple example on how to do the same with selenium. The catch here is with the Java library.

First let me explain what behavioural testing is. It is something like you write a story for a feature and based on the story you do your testing. You construct your stories on how the system would behave. Let’s consider http://www.google.com. If we had to write a story for it’s search functionality, the story in most of the cases would be as below.

“A person open google home page by typing the URL as http://www.google.com in the browser. Then he enters the search keyword (let’s assume ‘selenium’) and submits the page. Now something happens inside the system and the user is presented with links related to the keyword selenium”

Now let’s break it down to a behavioural specification. For the example taken, the specification may look as below.

scenario("A person searches for a keyword Selenium in Google") {
    given("A user is in google home page")
    open "http://www.google.com/"

    when("User does a search for the keyword Selenium")
    find "Search box"
    enter "Selenium"
    perform "Submit"

    then("Selenium link is listed in the search result")
  }

Now the question is how can we test this scenario with the help of selenium. This can be achieved through an opensource framework called ScalaTest. Below is an example code for achieving the same using ScalaTest and seleniumimport org.scalatest.FeatureSpec

import org.scalatest.GivenWhenThen
import org.openqa.selenium._
import org.openqa.selenium.firefox._
import java.util.concurrent.TimeUnit

class FirstScalaTest extends FeatureSpec with GivenWhenThen{
  private val driver = new FirefoxDriver
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS)
  scenario("A person searches for a keyword Selenium in Google") {
    given("A user is in google home page")
    driver.get("http://www.google.com/")

    when("User does a search for the keyword Selenium")
    val inputElement = driver.findElement(By.name("q"))
    inputElement.sendKeys("Selenium")
    val goButton = driver.findElement(By.id("gbqfb"))
    goButton.click()

    then("Selenium link is listed in the search result")
    assert(driver.findElementByPartialLinkText("Selenium").isDisplayed())
  }

}

When you run this class using sbt, your test result is published as a story. For example for the test given above the output would be as below.

Screen Shot 2013-01-05 at 7.32.07 PM

Behavioural driven technique is great way to do your acceptance testing. Keep testing, keep rocking :)

Starting with Selenium GRID

Want to take best advantage of Selenium, GRID is the answer. It acts as a load balancer, but for tests. It’s primary job is to distribute the tests to different nodes (machines) registered to the server which has the hub. Let’s get started with the same.

Software Requirements:

  1. Latest JDK and JRE
  2. Latest Selenium Server

Setting up the GRID environment:

Set up of the GRID environment is a two step process.
Step 1: Set up the Hub which acts as the Server
Step 2: Set up the Node which acts as the Client
The test is initiated at the Hub and Nodes run the test and send the results back to Hub (server).
Advantages of using GRID: Distributed tests mean saving time. Proper usage ensures 80% reduction in execution time.

Set up Hub:

Assuming that the Java environment is set and we have the Selenium server jar file in a folder, below are the steps to perform to start the hub.

Navigate to the folder which contains the selenium server in command prompt or terminal depending on the OS you use.

Issue the command “java -jar selenium-server-standalone-2.25.0.jar -role hub“. This command starts the selenium server as a GRID hub server. The role defines how the server is to started. Once the server is started, it looks like the following image.

Grid started and running

Once the server is running you can verify the state by navigating to http://localhost:4444 in a browser. In that case the screen will like as below.

GRID verification browser view

Note: If you have a firewall installed, add an exception for the port 4444 in firewall for http connections.

Set up node:

Every node should have java installed. It should also have the same selenium server jar file. Assuming we have the same, the command to register a machine as a node to already running hub is as below.

Navigate to the folder where the selenium server jar file is present and issue the following command.

java -jar selenium-server-standalone-2.25.0.jar -role node -hub http://ip-address-of-hub:4444/grid/register

Make sure you enter the ip address and do not copy-paste the url given here blindly. If you wish to register the same machine where node is running, instead of ip-address, localhost can be used.

Once the hub is running the command prompt looks something like the image below.

Node running state

Now to verify if a node is active, in the Hub machine open the GRID browser view (show in earlier screensho) and click on console link. It will show you the node detail and the browser it supports. The screen looks like as the below image.

With this the GRID set up is done. Let’s dive into a simple script which we can run through GRID. (The example is on WebDriver)

Sample Script:

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.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;

public class SampleTest {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
driver = new RemoteWebDriver(capability);
baseUrl = "https://www.google.co.in/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testUntitled() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("cheese");
driver.findElement(By.id("gbqfb")).click();
}

@After
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 see the script carefully, there is a bit of modification. Instead of directly invoking FirefoxDriver, we are using DesiredCapabilities.firefox() and instantiating the driver object through new RemoteWebDriver() which tell the script executor that this script is to be executed through selenium server. The server then allocates a node to the script where the script gets executed. Now explore GRID and happy testing. :)

How to Handle GWT suggestions using Selenium?

It is a very common pattern now a days that many web application are being developed using Google Web Toolkit and it can be very challenging to test such applications sometimes using selenium. For instance, last few days, I was struggling to go past a scenario where the suggest box of one field was masking another WebElement. For this reason the other WebElement was not getting located by Selenium and my test was failing. After many hit and trials, I found a way to solve this problem. The explanation of the solution goes as below.

Problem: 

Let’s assume that, there is text box called with id “city_id”. Below the field there is button with id “find”. While we type some city name in the city_id field, it suggest some cities with matching character. Then you select a city and click on the find button, you will displayed some result. Now the problem is, you type the whole city name and do and findElement for the find button. Since the suggestion box is open, selenium is unable to find the button and the test fails.

Solution:

Here, after doing a sendKeys operation with the city name to the city_id field, we need to do another sendKey operation to press keyboard enter. Now the button becomes visible and selenium can happily find the same. Below is the sample code on how to do it.


driver.findElement(By.xpath("//*[@id='city_id']")).sendKeys("Bangalore");
driver.findElement(By.xpath("//*[@id='city_id']")).sendKeys(Keys.Enter);
driver.findElement(By.xpath("//*[@id='find']")).click();

A Better Way of Writing Selenium Scripts [Part – 2]

Here I’m back with part 2 of the series. Here I would be explaining the test class. It’s basically the hybrid framework in detail.

The Algorithm:

Let’s start with the basic algorithm. Here for each new incoming data row, according to the property a conditional block is executed. Now the question might be why take such a complicated approach. The answer is this way, for any change there is minimalistic change/no change in the code which makes the code easily maintainable and reusable. Below is the algorithm.

While resultset has a new row
 if property = pagetitle
   Do some page title related operations
 if property = link
   Do some link related operation
 if property = textbox
   Do some Text Box related operation
 if property = image
   Do some image related operation
 if property = checkbox
   Do some check box related operation
 if property = dropdown
   Do some select related operation
 if property = radio
   Do some radio button related operation
 if property = text
   Do some text check related operation
 if property = url
   Do some url related operation
 if property = value
   Do some field value check operation
 if property = object
   Do some object finding operation
 if property = pop up window
   Do some pop window related operation
 end While

Remember each row contains a property field, a locator field, a locatortype field, a value field, an expectedResult field, a permission field and a name field. Let’s see what’s the purpose of each of these field.

  1. Property field: This field is a mandatory field. The value of this field determines which condition in the loop will be executed.
  2. Locator field: This field is optional and whenever not required can be left blank. This is used in combination with locatorType field to locate any object in a page. This is used by inner level of classes which will be explained a little later.
  3. LocatorType field: This field is mandatory when there is a corresponding locator value is available. This helps in locating objects in a page.
  4. Value: This field is optional and whenever not required can be left blank. This is used when there is a need of giving input to any field.
  5. ExpectedResult field: This field is again optional and whenever not required can be left blank. This is used whenever there is checkpoint or in laymans term a data equality check is needed.
  6. Permission field: This field is optional and whenever not required can be left blank. This field is used to control the object level operation to be performed. This will be explained in a later state.
  7. Name field: This field is optional and used for identification purpose in the result.

Now let’s go into one of the condition and see how it works. Let’s assume we are in condition “if property = dropdown”. The implementation for each condition is written in a different class. Lets consider the algorithm for DropDown class for this particular condition.

Assumption: We have 7 variables declared in the class to hold valued for each of the columns of the row under execution.

Function testDropDown()
 if permission = wait for some time
   if locatorType = xpath
     if isElementPresent(locator)
       select(By.xpath(value))
       sleep for 5 seconds
     else setActualResult(“Element Not Found”)
   if locatorType = cssSelector
     if isElementPresent(locator)
       select(By.cssSelector(value))
       sleep for 5 seconds
     else setActualResult(“Element Not Found”)
   if permission = “” or permission = null
     if locatorType = xpath
       if isElementPresent(locator)
         select(By.xpath(value))
       else setActualResult(“Element Not Found”)
     if locatorType = cssSelector
       if isElementPresent(locator)
         select(By.cssSelector(value))
       else setActualResult(“Element Not Found”)
 End Function

This is just the algorithm. An example of a concrete implementation is there in later stage. The algorithm can be modified to suite your need.

Example of Conditional Test Element class:

Below is the code for the DropDown class for the aforementioned algorithm of the same.


import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.awt.List;
@SuppressWarnings("unused")
public class DropDown {
 private WebDriver localDriver;
 String localProperty;
 String localLocator;
 String localLocatorType;
 String localValue;
 String localExpectedResult;
 String localPermission;
 String localName;
 String actualResult;
 String cause;

 public DropDown(WebDriver driver, String property, String locator, 
String locatorType, String value, String expectedResult, String permission, String name){
 localDriver = driver;
 localProperty = property;
 localLocator = locator;
 localLocatorType = locatorType;
 localValue = value;
 localExpectedResult = expectedResult;
 localPermission = permission;
 localName = name;
 cause = "";
 }

 public boolean testDropDown() throws Exception{
 if(isElementPresent(By.xpath(localLocator)) || isElementPresent(By.xpath(localLocator+"']")) || 
isElementPresent(By.cssSelector(localLocator)) || isElementPresent(By.name(localLocator)) || 
isElementPresent(By.id(localLocator))){
 try{
 if(localLocatorType.equals("xpath")){
 Select select = new Select(localDriver.findElement(By.xpath(localLocator)));
 if(localPermission.equals("wait for some time")){
 select.selectByVisibleText(localValue);
 Thread.sleep(5000);
 }
 else if(localPermission.equals("count")){
 int noOfElements=select.getOptions().toArray().length;
 System.out.println("There are "+noOfElements+" options in "+localName+" dropdown");
 }
 else if(localPermission.equals("all options")){
 List allOptions=(List) select.getOptions();
 System.out.println("All the options in the dropdown are as below:");
 for(int count=0; count<allOptions.getItemCount(); count++){
 System.out.println(allOptions.toString());
 }
 }
 else{
 select.selectByIndex(1);
 if(!localValue.equals(""))
 select.selectByVisibleText(localValue);
 }
 }
 else if(localLocatorType.equals("cssSelector")){
 Select select = new Select(localDriver.findElement(By.cssSelector(localLocator)));
 if(localPermission.equals("wait for some time")){
 select.selectByVisibleText(localValue);
 Thread.sleep(5000);
 }
 else if(localPermission.equals("count")){
 int noOfElements=select.getOptions().toArray().length;
 System.out.println("There are "+noOfElements+" options in "+localName+" dropdown");
 }
 else if(localPermission.equals("dynamic")){
 select.selectByIndex(1);
 }
 else if(localPermission.equals("all options")){
 List allOptions=(List) select.getOptions();
 System.out.println("All the options in the dropdown are as below:");
 for(int count=0; count<allOptions.getItemCount(); count++){
 System.out.println(allOptions.toString());
 }
 }
 else{
 select.selectByIndex(1);
 if(!localValue.equals(""))
 select.selectByVisibleText(localValue);
 }
 }
  }
 }
 catch (Exception e){
 setActualResult("Exception Occurred");
 setCause(e.getMessage());
 return false;
 }
 setActualResult("Element Present");
 return true;
 }
 else{
 setActualResult("Element Not Found");
 setCause("Element Not Found");
 return false;
 }
 }

public void setActualResult(String actualResult){
 this.actualResult = actualResult;
 }

public String getActualResult(){
 return actualResult;
 }

public void setCause(String cause){
 this.cause = cause;
 }

public String getCause(){
 return cause;
 }

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

I hope, this post is helpful to somebody. :)

A Better Way of Writing Selenium Scripts [Part - 1]

Many of us would be wordering what’s the best way to do scripting using selenium. Should we use ‘Data Driven Test Frameworks’, should we use ‘Keyword Driven Test Framework’ or should we combine both and use ‘Hybrid Test Framework’. Should we fetch the data from an excel sheet, or may be should we use XML files, or should we be more developer kind and use a Database instead. If you search on internet you will find many answers and arguments. Frankly speaking there is no defined best way to script using selenium. It all depends on the application under test, what would be the best way to test the same. Here I would be taking the the Hybrid Framework into consideration with the help of a Database to provide data to my scripts. Here I would be answering the question which arises after my post about the Hybrid framework which I wrote earlier sometime. I will explain a way to use the framework in an efficient manner. Contrary from my post about Hybrid Framework, the examples I would be using here would be of WebDriver as with the progress of Selenium, I have also started to explore the power of WebDriver now. So let’s start.

Something About Dividing the Test Modules:

So let’s start with going about designing test cases. What’s an efficient way of doing the same? Let’s take example of a site ‘www.yahoo.com‘ which gives details about different mobile phones. Here taking modularity into consideration, each functionality should be considered as a test module. The smaller the test module is, the better it is for automation. Always remember to divide an application to smaller modules keeping automation in mind which is different from manual testing. Here let me give an example. When you open www.yahoo.com, we can consider sign in as one test module, mail as one test module, Trending now can be one test module, the Yahoo Sites column can be one module. Now we need to design test cases in each module. Let’s take the example of sign in module. For sign in module we can write the test cases as below.

Sl No Action Expected Result
1 Click SIGN IN link in the home page. Sign in page should open with page title “Sign in to Yahoo India”
2 Check if Yahoo ID field is there Yahoo ID field should be present
3 Check if Password field is there Password field should be there
4 Check if Keep me signed in checkbox is there Keep me signed in checkbox should be present
5 Check if sign in button is present Sign in button should be present
6 Enter valid login information and click on Sign in button The user should be able to sign in and page should redirect back to yahoo home page.

Similarly many test cases are possible for this scenario. Let me limit myself here and we’ll go about automating these step for the example. Similarly we can write test cases for different test modules.

Designing data model to test different modules effectively:

How do we design our test modules and put them into the test framework so that we can test them independently. This can be achieved with above approach of designing test modules to the smallest unit so that they are independent of each other. Why do so? Let’s assume that we have designed our test cases in such a way that dependencies are there and when we run the automation script for them, the whole suite runs with all dependencies. The next question is, what’s the problem with that? Let’s say there is an enhancement in login module. Now the question arises why test let’s the search module for the same and waste time. We should be able test only the module where changes were there to achieve the effectiveness that we are looking for. Let’s consider we have 4 test modules as below.

  • Sign in
  • Search
  • Mail
  • Yahoo Site Module

Note: I’m considering only these for showing the examples only

Now comes the use of Database. Let’s create a master table which store information about different modules. Let’s call the table auto_tabData. The table looks as below.

Id Functionality TableForFunctionality
1 Sign in auto_signInData
2 Search auto_searchData
3 Mail auto_mailData
4 Yahoo Site Module auto_yahooSiteModuleData

Here in this table, for each functionality, we record the table name which hold the data for the same. Now lets design the table for Sign in functionality. Let’s say the table for Sign in functionality looks as below. (Note: The table is designed to suit the hybrid framework explained in my earlier post)

Property Locator LocatorType Value ExpectedResult Permission Name
pagetitle Yahoo! India Home Page Title
link //div[@id='default-p_30345710_cec-bd']/a/em xpath click Sign in link
pagetitle Sign in to Yahoo! India Sign in page title
textbox #username cssSelector Your actual username type User ID field
textbox #passwd cssSelector Your actual password type Password field
checkbox #persistent cssSelector click Keep me signed in checkbox
link //div[@id='submit']/button xpath click Submit button
value //div[@id='default-p_30345710_d0c-bd']/a/em xpath Hi, Your Name Welcome message in yahoo home page

Similarly let’s assume we have data tables for other functionalities too. Keeping all these details in mind, we’ll see in the next section on how to go about designing our test suite.

Designing the class model to accommodate the data model effectively:

In the previous section we saw the data model design. Now in this section we’ll see how to use them effectively. To do so, we should design our classes in three step. Basically there will be 3 high level classes.

  • 1st one’s purpose is to pass the functionalities which are to be tested.
  • 2nd one’s purpose is to get the table name from the DB which will be executed according to the class names passed from the 1st class and call the 3rd driver class which executes the test.
  • 3rd one is the driver class which runs the test according to the data passed from the 1st class.

Below are the code excerpts on how these classes work. Let’s name the first type of class as ‘UserDefinedTest‘. The class looks as below.

import org.testng.annotations.*;

public class UserDefinedTest {
 @Test
 public void defineTest() throws Exception {
 /*
 * Mention the Id(s), functionality(ies) here in the below 2
 * dimensional array (for multiple pages and functionalities, please
 * enter in the order of execution)
 */
 String[][] pageFuctionalities = { { "1", "Sign in" },{ "2", "search" } };
 AppTest appTest = new AppTest();
 appTest.setPageFunctionalities(pageFuctionalities);
 appTest.setBaseURL("http://www.yahoo.com/");
 appTest.setOutputFileName("outputMyTest");
 appTest.setScreenshotName("Screenshot");
 appTest.runTest();
 }
}

Now let’s name the 2nd type of class ‘AppTest‘. This class looks as below.

import org.testng.annotations.*;
import java.io.StringWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("unused")
public class AppTest {
 private String pageFunctionalities[][];
 private String baseURL;
 private String outputFileName;
 private String screenshotName;

public void setPageFunctionalities(String pageFunctionalities[][]) {
 this.pageFunctionalities = pageFunctionalities;
 }

public void setBaseURL(String baseURL) {
 this.baseURL = baseURL;
 }

public void setOutputFileName(String outputFileName) {
 this.outputFileName = outputFileName;
 }

public void setScreenshotName(String screenshotName) {
 this.screenshotName = screenshotName;
 }

@Test
 public void runTest() throws Exception {
 Connection conn = null;
 try {
 Class.forName("com.mysql.jdbc.Driver");
 conn = DriverManager
 .getConnection(
 "jdbc:mysql://connection_string/database_name",
 "user_name", "password");
 } catch (SQLException e) {
 e.printStackTrace();
 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 }
 List tables = new ArrayList();
 System.out.println("The lenth of the two dimensional array is "
 + pageFunctionalities.length);
 for (int i = 0; i < pageFunctionalities.length; i++) {
 ResultSet resultSet = null;
 System.out.println("ID: " + pageFunctionalities[i][0] + " Functionality: "
 + pageFunctionalities[i][1]);
 PreparedStatement preparedStatement = conn
 .prepareStatement("select TableForFunctionality from auto_tabData where Id = '"
 + pageFunctionalities[i][0]
 + "' and Functionality = '"
 + pageFunctionalities[i][1] + "'");
 resultSet = preparedStatement.executeQuery();
 System.out.println("Query Execution Count: " + i);
 while (resultSet.next()) {
 tables.add(resultSet.getString(1));
 }
 }
 System.out.println("The tables to be executed are as below");
 for (String val : tables) {
 System.out.println(val);
 }
 TestConfig testConfig = new TestConfig();
 testConfig.setBaseUrl(baseURL);
 testConfig.setOutputFileName(outputFileName);
 testConfig.setScreenshotName(screenshotName);
 testConfig.setUp();
 for (String val : tables) {
 System.out.println("Table being executed: " + val);
 testConfig.setTableName(val);
 testConfig.testElements();
 }
 testConfig.tearDown();
 }
}

Now comes the 3rd type of class. Let’s name it ‘TestConfig‘ which looks as below.

import com.pilanisoftlabs.TestElements.*;
import com.pilanisoftlabs.TestElements.Image;
import java.util.concurrent.TimeUnit;
import jxl.format.*;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.write.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import jxl.*;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.sql.*;

@SuppressWarnings("unused")
public class TestConfig {
 private WebDriver driver;
 private String baseUrl = "http://www.google.com/";
 private StringBuffer verificationErrors = new StringBuffer();
 private int counter = 1;
 private boolean result;
 private String actualResult;
 private WritableWorkbook workbook;
 private WritableSheet sheet;
 private int rowCounter = 4;
 private Integer passCounter = 0;
 private Integer failCounter = 0;
 private String tableName = "";
 private String outputFileName = "";
 private String screenshotName = "";

public void setBaseUrl(String baseUrl) {
 this.baseUrl = baseUrl;
 }

public void setTableName(String tableName) {
 this.tableName = tableName;
 }

public void setOutputFileName(String outputFileName) {
 this.outputFileName = outputFileName;
 }

public void setScreenshotName(String screenshotName) {
 this.screenshotName = screenshotName;
 }

@BeforeClass
 public void setUp() throws Exception {
 driver = new FirefoxDriver();
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 driver.get(baseUrl);

 workbook = Workbook.createWorkbook(new File("test-output/"
 + outputFileName + ".xls"));
 sheet = workbook.createSheet("output", 0);
 WritableFont writableFont = new WritableFont(WritableFont.ARIAL, 10,
 WritableFont.BOLD);
 WritableCellFormat writableCellFormat = new WritableCellFormat(
 writableFont);

 Label l1 = new Label(0, 3, "Name", writableCellFormat);
 Label l2 = new Label(1, 3, "Expected Result", writableCellFormat);
 Label l3 = new Label(2, 3, "Actual Result", writableCellFormat);
 Label l4 = new Label(3, 3, "Cause", writableCellFormat);
 Label l5 = new Label(4, 3, "Status", writableCellFormat);
 sheet.addCell(l1);
 sheet.addCell(l2);
 sheet.addCell(l3);
 sheet.addCell(l4);
 sheet.addCell(l5);
 }

@Test()
 public void testElements() throws Exception {
 Connection conn = null;
 try {
 Class.forName("com.mysql.jdbc.Driver");
 conn = DriverManager
 .getConnection(
 "jdbc:mysql://connection_string/database_name",
 "user_name", "password");
 } catch (SQLException e) {
 e.printStackTrace();
 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 }
 ResultSet resultSet = null;
 PreparedStatement preparedStatement = conn
 .prepareStatement("select * from " + tableName);
 resultSet = preparedStatement.executeQuery();

 while (resultSet.next()) {
 String property = resultSet.getString(1);
 String locator = resultSet.getString(2);
 String locatorType = resultSet.getString(3);
 String value = resultSet.getString(4);
 String expectedResult = resultSet.getString(5);
 String permission = resultSet.getString(6);
 String name = resultSet.getString(7);

 System.out.println("Current Row is " + property + ", " + locator
 + ", " + locatorType + ", " + value + ", " + expectedResult
 + ", " + permission + ", " + name);

 // Start of Page Title testing block
 if (property.equals("pagetitle")) {
 PageTitle title = new PageTitle(driver, property, locator,
 locatorType, value, expectedResult, permission, name);
 result = title.testPageTitle();
 actualResult = title.getActualResult();
 updateResult(result, name, expectedResult, title.getCause());
 }
 // End of Page Title testing block

 // Start of Link testing block, used to click on links and get title
 // tag of links
 if (property.equals("link")) {
 Link link = new Link(driver, property, locator, locatorType,
 value, expectedResult, permission, name);
 result = link.testLink();
 actualResult = link.getActualResult();
 updateResult(result, name, expectedResult, link.getCause());
 String fileLocation = "test-output/Screenshot/"
 + screenshotName + counter + ".png";
 ScreenShot ss = new ScreenShot(driver, fileLocation);
 ss.takeScreenshot();
 counter++;
 }
 // End of Link testing block

 // Start of Image testing block used to click on images and to test
 // alttag for them
 if (property.equals("image")) {
 Image image = new Image(driver, property, locator, locatorType,
 value, expectedResult, permission, name);
 result = image.testImage();
 actualResult = image.getActualResult();
 updateResult(result, name, expectedResult, image.getCause());
 }
 // End of Image testing block

 // Start of Dropdown testing block, used to select a value from
 // dropdown, to find out number of elements and to show all the
 // elements
 if (property.equals("dropdown")) {
 DropDown dropDown = new DropDown(driver, property, locator,
 locatorType, value, expectedResult, permission, name);
 result = dropDown.testDropDown();
 actualResult = dropDown.getActualResult();
 updateResult(result, name, expectedResult, dropDown.getCause());
 }
 // End of Dropdown testing block

 // Start of Text Box testing block, used to test if text box is
 // editable, to write values in them
 if (property.equals("textbox")) {
 TextBox textBox = new TextBox(driver, property, locator, locatorType, value, expectedResult,
 permission, name);
 result = textBox.testTextBox();
 actualResult = textBox.getActualResult();
 updateResult(result, name, expectedResult, textBox.getCause());
 }
 // End of Text Box testing block

 // Start of Radio Button testing block, used to test if radio button
 // is clickable, to click a particual radio button
 if (property.equals("radio")) {
 Radio radio = new Radio(driver, property, locator, locatorType,
 value, expectedResult, permission, name);
 result = radio.testRadio();
 actualResult = radio.getActualResult();
 updateResult(result, name, expectedResult, radio.getCause());
 }
 // End of Radio Button testing block

 // Start of Check Box testing block, used to test if check box is
 // clickable, to select some check boxes
 if (property.equals("checkbox")) {
 CheckBox checkBox = new CheckBox(driver, property, locator,
 locatorType, value, expectedResult, permission, name);
 result = checkBox.testCheckBox();
 actualResult = checkBox.getActualResult();
 updateResult(result, name, expectedResult, checkBox.getCause());
 }
 // End of Check Box testing block

 // Start of text checking block, used to test presence of specific
 // text in a page
 if (property.equals("text")) {
 Text text = new Text(driver, property, locator, locatorType,
 value, expectedResult, permission, name);
 result = text.testText();
 actualResult = text.getActualResult();
 updateResult(result, name, expectedResult, text.getCause());
 }
 // End of text checking block

 // Start of URL testing block, used to get the URL being displayed
 // for a page
 if (property.equals("url")) {
 Url url = new Url(driver, property, locator, locatorType,
 value, expectedResult, permission, name);
 url.setBaseURL(baseUrl);
 result = url.testUrl();
 actualResult = url.getActualResult();
 updateResult(result, name, expectedResult, url.getCause());
 }
 // End of URL testing block

 // Start of value testing block used to test the value present in
 // any object
 if (property.equals("value")) {
 ValueTest valueTest = new ValueTest(driver, property, locator,
 locatorType, value, expectedResult, permission, name);
 result = valueTest.testValue();
 actualResult = valueTest.getActualResult();
 updateResult(result, name, expectedResult, valueTest.getCause());
 }
 // End of value testing block

 // Start of Object finder block
 if (property.equals("object")) {
 ObjectFinder objectFinder = new ObjectFinder(driver, property,
 locator, locatorType, value, expectedResult,
 permission, name);
 result = objectFinder.testObjectPresent();
 actualResult = objectFinder.getActualResult();
 updateResult(result, name, expectedResult,
 objectFinder.getCause());
 }
 // End of object finder block

 if (property.equals("pop up window")) {
 NewWindow newWindow = new NewWindow(driver, property, locator,
 locatorType, value, expectedResult, permission, name);
 result = newWindow.testNewWindow();
 actualResult = newWindow.getActualResult();
 updateResult(result, name, expectedResult, newWindow.getCause());
 }
 }

}

@AfterClass
 public void tearDown() throws Exception {
 WritableFont writableFont = new WritableFont(WritableFont.ARIAL, 10,
 WritableFont.BOLD);
 WritableCellFormat writableCellFormat = new WritableCellFormat(
 writableFont);
 Label l1 = new Label(0, 0, "Steps Passed", writableCellFormat);
 Label l2 = new Label(1, 0, passCounter.toString(), writableCellFormat);
 sheet.addCell(l1);
 sheet.addCell(l2);
 Label l3 = new Label(0, 1, "Steps Failed", writableCellFormat);
 Label l4 = new Label(1, 1, failCounter.toString(), writableCellFormat);
 sheet.addCell(l3);
 sheet.addCell(l4);
 workbook.write();
 workbook.close();
 System.out.println("Closed the file ...");
 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;
 }
 }

private void updateResult(boolean bool, String name, String expectedResult,
 String cause) throws Exception {
 Label label1 = new Label(0, rowCounter, name);
 Label label2 = new Label(1, rowCounter, expectedResult);
 Label label3 = new Label(2, rowCounter, actualResult);
 Label label4 = new Label(3, rowCounter, cause);
 sheet.addCell(label1);
 sheet.addCell(label2);
 sheet.addCell(label3);
 sheet.addCell(label4);
 if (result) {
 WritableFont writableFont = new WritableFont(WritableFont.ARIAL,
 10, WritableFont.BOLD);
 WritableCellFormat writableCellFormat = new WritableCellFormat(
 writableFont);
 writableCellFormat.setBackground(Colour.GREEN);
 Label label5 = new Label(4, rowCounter, "Pass", writableCellFormat);
 passCounter++;
 sheet.addCell(label5);
 } else {
 WritableFont writableFont = new WritableFont(WritableFont.ARIAL,
 10, WritableFont.BOLD);
 WritableCellFormat writableCellFormat = new WritableCellFormat(
 writableFont);
 writableCellFormat.setBackground(Colour.RED);
 Label label5 = new Label(4, rowCounter, "Fail", writableCellFormat);
 failCounter++;
 sheet.addCell(label5);
 }
 rowCounter++;
 }

}

Rest of this post, I would be explaining the next part. There we’ll concentrate more on the 3rd type of the class. Stay tuned…. :)

How to work with pop up windows using WebDriver?

It’s been quite some time since my last post. Here is problem we face many times. As time goes by coding standard rises and now a developer code in such a way that, it’s difficult to find different elements with names. One such difficulty come, when there is a pop up window appears on clicking a link and that has no name. Even with Selenium IDE, it’s difficult to find the handler name. What to do in such scenarios when we need to do some operation in the pop up window. There is a solution to it. What we have to do is, we need to use getWindowHandles() method that WebDriver provides. It generally returns a set of all the window handle that are active. The set is generally a set of Strings. Below is a sample code that can be used to select a pop up window.

public boolean testNewWindow(){
 String currentHandle = driver.getWindowHandle();
 Set handles = driver.getWindowHandles();
 handles.remove(currentHandle);
 if (handles.size() > 0) {
 try{
 driver.switchTo().window(handles.iterator().next());
 return true;
 }
 catch(Exception e){
 System.out.println(e.getMessage());
 return false;
 }
 }
 System.out.println("Did not find window");
 return false;
 }

Here the variable currentHandle holds the current window identification and the set handles hold all the window handle through which we iterate. Once you are done  Hope this will make someone’s life a little easier. :)

A way to test Object by Object using selenium

Many of us must be trying to find the best way to do automation testing using selenium. And if we write our script in the same class, it becomes too long and difficult to manage. To tackle the same one can always follow the hybrid framework mentioned in my earlier post. But is it the best way to do it? The answer depends on how do we want to code our script. There is a way which I have implemented recently, which gives an option to reuse the code in an efficient manner. The details of the approach are as follows.

Here, in this approach, what I am trying to do is create separate classes as per the properties we will be testing. Let’s say the table below drives my test.

Property Locator LocatorType Value ExpectedResult Permission Name
url http://ibnlive.in.com/ open
pagetitle CNN-IBN Live News, Breaking News, Top Headlines, Live/Current News Alerts

Let’s now look at the first row of the table. Property for the first row is url. So the logic would be,

if(property = "url") then
create url object.
use the object to do url related operation.

So our requirement now is a class called ‘Url’ which contains some property and methods to do testing related to URL’s. Below is the sample class. (The class is a sample. It depends on the user what to write as the business logic for the same)


import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
@SuppressWarnings("unused")
public class Url {
 private WebDriver localDriver;
 String localProperty;
 String localLocator;
 String localLocatorType;
 String localValue;
 String localExpectedResult;
 String localPermission;
 String localName;
 String actualResult;

 public Url(WebDriver driver, String property, String locator, String locatorType, String value, 
String expectedResult, String permission, String name){
 localDriver = driver;
 localProperty = property;
 localLocator = locator;
 localLocatorType = locatorType;
 localValue = value;
 localExpectedResult = expectedResult;
 localPermission = permission;
 localName = name;
 }

 public boolean testUrl() throws Exception{
 if(localPermission.equals("open")){
 localDriver.get(localLocator);
 setActualResult("Opened URL");
 return true;
 }
 else
 {
 String url = localDriver.getCurrentUrl();
 //assertEquals("In Page: "+localDriver.getTitle(), localExpectedResult, url);
 if(localExpectedResult.equals(url)){
 setActualResult(url);
 return true;
 }
 else {
 setActualResult(url);
 return false;
 }
 }

}

public void setActualResult(String actualResult){
 this.actualResult = actualResult;
 }

public String getActualResult(){
 return actualResult;
 }

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

This class has all the properties defined as the column names of the table. Also there is a constructor available to create the object of the class type. The business logic is written in the testUrl method which is dependent on the parameters passed to the method and it returns a boolean type value (either true or false). Depending on the result returned the final result of the test step is decided. Similarly one more sample class for the second row property (pagetitle) would be as below.


package TestElements;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
@SuppressWarnings("unused")
public class PageTitle {
 private WebDriver localDriver;
 String localProperty;
 String localLocator;
 String localLocatorType;
 String localValue;
 String localExpectedResult;
 String localPermission;
 String localName;
 String actualResult;

 public PageTitle(WebDriver driver, String property, String locator, String locatorType, String value, 
String expectedResult, String permission, String name){
 localDriver = driver;
 localProperty = property;
 localLocator = locator;
 localLocatorType = locatorType;
 localValue = value;
 localExpectedResult = expectedResult;
 localPermission = permission;
 localName = name;
 }

 public boolean testPageTitle() throws Exception{
 String title = localDriver.getTitle();
 setActualResult(title);
 //assertEquals("In Page: "+title, localExpectedResult, title);
 if(localExpectedResult.equals(title)){
 return true;
 }
 else{
 return false;
 }
 }

public void setActualResult(String actualResult){
 this.actualResult = actualResult;
 }

public String getActualResult(){
 return actualResult;
 }

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

Here the testPageTitle method does all the work. Below is another sample class for a different page element let’s say textbox.


package TestElements;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
@SuppressWarnings("unused")
public class TextBox {
 private WebDriver localDriver;
 String localCashCoupon;
 String localTicketNumber;
 String localProperty;
 String localLocator;
 String localLocatorType;
 String localValue;
 String localExpectedResult;
 String localPermission;
 String localName;
 String actualResult;

 public TextBox(WebDriver driver, String cashCoupon, String ticketNumber, String property, String locator, 
String locatorType, String value, String expectedResult, String permission, String name){
 localDriver = driver;
 localCashCoupon = cashCoupon;
 localTicketNumber = ticketNumber;
 localProperty = property;
 localLocator = locator;
 localLocatorType = locatorType;
 localValue = value;
 localExpectedResult = expectedResult;
 localPermission = permission;
 localName = name;
 }

 public TextBox(WebDriver driver, String value, String locator){
 localDriver = driver;
 localValue = value;
 localLocator = locator;
 }

public boolean testTextBox() throws Exception{
 //assertTrue("In Page: "+localDriver.getTitle(), isElementPresent(By.xpath(localLocator)) ||
 isElementPresent(By.cssSelector(localLocator)) || isElementPresent(By.name(localLocator)) ||
 isElementPresent(By.id(localLocator)));
 if(isElementPresent(By.xpath(localLocator)) || isElementPresent(By.cssSelector(localLocator)) ||
 isElementPresent(By.name(localLocator)) || isElementPresent(By.id(localLocator))){
 if(localPermission.equals("editability")){
 if(localLocatorType.equals("xpath")){
 //assertTrue("In Page: "+localDriver.getTitle(), localDriver.findElement(By.xpath(localLocator)).isEnabled());
 if(localDriver.findElement(By.xpath(localLocator)).isEnabled()){
 setActualResult("Editable");
 return true;
 }
 else {
 setActualResult("Not Editable");
 return false;
 }
 }

else if(localLocatorType.equals("cssSelector")){
 //assertTrue("In Page: "+localDriver.getTitle(), localDriver.findElement(By.cssSelector(localLocator)).isEnabled());
 if(localDriver.findElement(By.cssSelector(localLocator)).isEnabled()){
 setActualResult("Editable");
 return true;
 }
 else{
 setActualResult("Not Editable");
 return false;
 }
 }

else if(localLocatorType.equals("id")){
 //assertTrue("In Page: "+localDriver.getTitle(), localDriver.findElement(By.id(localLocator)).isEnabled());
 if(localDriver.findElement(By.id(localLocator)).isEnabled()){
 setActualResult("Editable");
 return true;
 }
 else{
 setActualResult("Not Editable");
 return false;
 }
 }

else if(localLocatorType.equals("name")){
 //assertTrue("In Page: "+localDriver.getTitle(), localDriver.findElement(By.name(localLocator)).isEnabled());
 if(localDriver.findElement(By.name(localLocator)).isEnabled()){
 setActualResult("Editable");
 return true;
 }
 else{
 setActualResult("Not editable");
 return false;
 }
 }

}
 if(localPermission.equals("type")){
 if(localLocatorType.equals("xpath")){
 localDriver.findElement(By.xpath(localLocator)).clear();
 localDriver.findElement(By.xpath(localLocator)).sendKeys(localValue);
 }
 else if(localLocatorType.equals("cssSelector")){
 localDriver.findElement(By.cssSelector(localLocator)).clear();
 localDriver.findElement(By.cssSelector(localLocator)).sendKeys(localValue);
 }
 else if(localLocatorType.equals("id")){
 localDriver.findElement(By.id(localLocator)).clear();
 localDriver.findElement(By.id(localLocator)).sendKeys(localValue);
 }
 else if(localLocatorType.equals("name")){
 localDriver.findElement(By.name(localLocator)).clear();
 localDriver.findElement(By.name(localLocator)).sendKeys(localValue);
 }
 setActualResult("Value Entered");
 return true;
 }
 if(localPermission.equals("date")){
 DynamicDate date = new DynamicDate();
 String testDate = date.getTestDate();

if(localLocatorType.equals("xpath")){
 localDriver.findElement(By.xpath(localLocator)).clear();
 localDriver.findElement(By.xpath(localLocator)).sendKeys(testDate);
 }
 else if(localLocatorType.equals("cssSelector")){
 localDriver.findElement(By.cssSelector(localLocator)).clear();
 localDriver.findElement(By.cssSelector(localLocator)).sendKeys(testDate);
 }
 else if(localLocatorType.equals("id")){
 localDriver.findElement(By.id(localLocator)).clear();
 localDriver.findElement(By.id(localLocator)).sendKeys(testDate);
 }
 else if(localLocatorType.equals("name")){
 localDriver.findElement(By.name(localLocator)).clear();
 localDriver.findElement(By.name(localLocator)).sendKeys(testDate);
 }
 setActualResult("Date Entered");
 return true;
 }
 }

}
 else {
 setActualResult("Element Not Found");
 return false;
 }
 return true;
 }

 public void typeValue(){
 localDriver.findElement(By.xpath(localLocator)).clear();
 localDriver.findElement(By.xpath(localLocator)).sendKeys(localValue);
 }

public void setActualResult(String actualResult){
 this.actualResult = actualResult;
 }

public String getActualResult(){
 return actualResult;
 }

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

Here the business logic is present in the testTextBox method.

Now how to make use of them. Let’s assume we are using a Database where the table is residing. So we need to create another class which will drive the test. Let’s call it “TestDriver” class. Below is the sample class that is required for driving our test.


//import the required libraries

//import the test classes that you already have written

public class TestDriver{

private WebDriver driver;
 private String baseUrl="http://www.redbus.in/";
 private StringBuffer verificationErrors = new StringBuffer();

private boolean result;
 private String actualResult;

@BeforeClass
 public void setUp() throws Exception {

driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get(baseUrl);

}

@Test()
 public void testElements() throws Exception {
 Connection conn=null;
 try {
 Class.forName("com.mysql.jdbc.Driver");
 conn = DriverManager.getConnection("connection string", "user name", "password");
 }
 catch (SQLException e) {
 e.printStackTrace();
 }
 catch (ClassNotFoundException e) {
 e.printStackTrace();
 }
 ResultSet resultSet = null;
 PreparedStatement preparedStatement = conn.prepareStatement("select * from YourTableName");
 resultSet = preparedStatement.executeQuery();

while(resultSet.next()){
 String property = resultSet.getString(1);
 String locator = resultSet.getString(2);
 String locatorType = resultSet.getString(3);
 String value = resultSet.getString(4);
 String expectedResult = resultSet.getString(5);
 String permission = resultSet.getString(6);
 String name = resultSet.getString(7);

System.out.println("Current Row is "+property+", "+locator+", "+locatorType+", "+value+", "+expectedResult+", "+permission+", "+name);

//Start of Page Title testing block
 if(property.equals("pagetitle")){
 PageTitle title = new PageTitle(driver, property, locator, locatorType, value, expectedResult, permission, name);
 result = title.testPageTitle();
 actualResult = title.getActualResult();
 updateResult(result,name,expectedResult);
 }
 //End of Page Title testing block

//Start of Text Box testing block, used to test if text box is editable, to write values in them
 if(property.equals("textbox")){
 TextBox textBox = new TextBox(driver, cashCoupon, ticketNumber, property, locator, locatorType, value, expectedResult, permission, name);
 result = textBox.testTextBox();
 actualResult = textBox.getActualResult();
 updateResult(result,name,expectedResult);
 }
 //End of Text Box testing block

//Start of URL testing block, used to get the URL being displayed for a page
 if(property.equals("url")){
 Url url = new Url(driver, property, locator, locatorType, value, expectedResult, permission, name);
 result = url.testUrl();
 actualResult = url.getActualResult();
 updateResult(result,name,expectedResult);
 }
 //End of URL testing block

}

}

@AfterClass
 public void tearDown() throws Exception {
 driver.close();
 driver.quit();
 //service.stop();
 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;
 }
 }

private void updateResult(boolean bool, String name, String expectedResult) throws Exception{
 Label label1 = new Label(0,rowCounter,name);
 Label label2 = new Label(1,rowCounter,expectedResult);
 Label label3 = new Label(2,rowCounter,actualResult);
 sheet.addCell(label1);
 sheet.addCell(label2);
 sheet.addCell(label3);
 if(result){
 WritableFont writableFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
 WritableCellFormat writableCellFormat = new WritableCellFormat(writableFont);
 writableCellFormat.setBackground(Colour.GREEN);
 Label label4 = new Label(3,rowCounter,"Pass",writableCellFormat);
 passCounter++;
 sheet.addCell(label4);
 }
 else{
 WritableFont writableFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
 WritableCellFormat writableCellFormat = new WritableCellFormat(writableFont);
 writableCellFormat.setBackground(Colour.RED);
 Label label4 = new Label(3,rowCounter,"Fail",writableCellFormat);
 failCounter++;
 sheet.addCell(label4);
 }
 rowCounter++;
 }

}

Let’s concentrate on the Test method and ignore the rest part. (Anyways the code is a sample and many snippets are deleted. It will not work by copy pasting the same). So to make use of the test classes, we need to create the objects of the classes. Then we need to call the method defined the classes using the object. So here the objects are created depending on the property type defined in the table and bases on the same each block is executed. The test goes on in loop for as many rows present in the table.

* Selenium 2 is used to describe the code blocks

* The codes mentioned here are snippets and many thing are deleted. They may not work if directly copied

* The sample mentioned here generates a custom output. TestNG capabilities can be used if the user prefers by using assertions instead of if else block the the test classes by making the return type of the method void.

Setting up IntellijIDEA for Selenium

Here we’ll see how to configure intellijIDEA to set up test environment using selenium. Before starting anything, let’s build the environment prior to the configuration of project in intellijIDEA. Below are the checks that we should make:

1. Make sure we have the latest JDK installed in our system which is JDK 6.

2. Collect all the external library file required to do the testing successfully. The are as below.

  • jxl.jar
  • latest testNG jar file
  • the selenium packages (selenium server 2.9 and java version of selenium client drivers)
Once these files are in place, let’s start the configuration.
Step 1: Create the Project
The first step is to create a project. To do so let’s create a project by selecting File – > New Project. Once you click New Project, the following pop up comes up.
Now, let the “Create project from scratch” be selected and click on next. The next screen is as below.
Now provide a name (let’s say ‘Automation’) for the project and select a location where to create the same. Let the Java module be selected and click on next. In the next page, click next. In the next page click on finish. If it asks to select JDK in between, then select your JDK folder which would be there in program files.
Once the project is created the screen looks like the below image.
Step 2: Configure the Project
Now expand the project folder (in this case Automation). Right click on the project name and select New – > Directory. Name the folder as lib. Go to it’s physical location and place the selenium library files, jxl and testNG jar files.  Now we need these file to be referenced by the project to use them. To do so, we need to follow the below steps.
Click on File -> Project Structure. The following window opens up.
Now click on the Modules tab on the left side. Click on the dependency tab on the right side. This looks like as below.
Click on the Add button and click on Library. The window will be shown like the below image.
Now click on Attach Jar Directories. Then select the lib folder and click ok. Enter a library name like Selenium libraries and click Ok. Now all the dependencies are set. Once this is done, right click on the project and create a new directory named resources. There you can place the data sheet for your test. The final folder structure will be shown in the image below.
Now the Project is set. Create new classes in src folder and you are all set. Happy testing :)

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.