Selenium WebDriver Example / Sample test application - Learn Selenium / Learn WebDriver

For all the newbies who are trying to learn selenium there are very few examples except for this one.
If you already know how to configure eclipse and webdriver then you are reading the right post.
For those who want some info on configuring eclipse - check this earlier post.

The best thing I could think of was automating my own blog as an example.
Here are the steps:
  1. Launch the browser
  2. Navigate to
  3. In the customized google search field type "Selenium"
  4. Click on search
  5. Validate the search results are displayed
  6. Close the browser
Create a new package
Create a new class under that
Now you can either record using selenium IDE and Export the test case as JUnit 4 (WebDriver) and save the file as as a "".java or use any tool (Six tools for Selenium Object Identification) to get the object properties to directly use in the webdriver test case.

So we are all set to start coding

This is how the raw test case would look like:

package testSelenium;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertTrue;

public class FirstClass {
private WebDriver driver;

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

public void tearDown() throws Exception {

public void testSearchExportedFromIDE() throws Exception {
String baseUrl = "";
WebElement searchField = driver.findElement("search"));

WebElement searchResult = driver.findElement(By.className("gs-visibleUrl"));
String expected = "";
String actual = searchResult.getText();

It needs some cleaning up. Note that it is good enough to be executed but this is just a starting point.
You can play around by changing the properties and using other identification types
Check this page for more information and to understand and learn selenium.

A few things that can be changed:
1. Firefox Profile should be the default profile
2. While debugging you will need a lot of message boxes so just add this snippet
//import javax.swing.JOptionPane;  //JOptionPane.showMessageDialog(null,actual );
3. Take screenshots on failures
The test case can be further transformed into something that uses page object model and that may be easier to read.

The Page Object pattern represents the screens of your web app as a series of objects - Read this!
Something more readable + PO model would look like this:

package testSelenium;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;

import static junit.framework.Assert.assertTrue;

public class FirstClass {
private WebDriver driver;

public void setUp() throws Exception {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("default");
driver = new FirefoxDriver(ffprofile);

public void tearDown() throws Exception {

public void testSearchExportedFromIDE() throws Exception {
Homepage home = new Homepage(driver);
SearchResultPage searchResult = home.searchFor("Selenium");
String expected =;
String actual = searchResult.getHeadLine();
//JOptionPane.showMessageDialog(null,actual );

This needs two support classes, therefore add two new classes:

package testSelenium;

import org.openqa.selenium.*;

public class Homepage {
private WebDriver driver;

public Homepage(WebDriver driver) {
this.driver = driver;
String baseUrl = "";
driver.get(baseUrl + "/");

public SearchResultPage searchFor(String location) {
try {
WebElement searchField = driver.findElement("search"));
} catch (RuntimeException e) {
takeScreenShot(e, "searchError");
return new SearchResultPage(driver);

private void takeScreenShot(RuntimeException e, String fileName) {
File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File(fileName + ".png"));
} catch (IOException ioe) {
throw new RuntimeException(ioe.getMessage(), ioe);
throw e;


package testSelenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class SearchResultPage {
private WebDriver driver;
public SearchResultPage(WebDriver driver) {
this.driver = driver;
if (!driver.getTitle().contains("Go gaga over testing")) {
throw new IllegalStateException("This is not Go gaga over testing: " + driver.getCurrentUrl());

public String getHeadLine() {
WebElement searchResult = driver.findElement(By.className("gs-visibleUrl"));
return searchResult.getText();

If you are successful doing this with any of your web pages. You are now ready to dive in deep , start by reading all these documents and practicing a lot!
Happy Learning!


UnreachableBrowserException: Error communicating with the remote browser. It may have died !

So this is something I learnt the hardway , all of a sudden the selenium scripts throw an error:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.

I am not sure which one might work for you but I am sure things that will not work:
1. Upgarding firefox or any browser
2. Adding/Deleting the jar files
3. Changing the driver to instantiate the browser
4. Killing or trying to find orphan processes
  • Cherck for compatibilty of browser with selenium
  • Make sure that there are no warnings in your code 
  • Open the browser (in my case firefox)
    Go to the address bar and type about:config
    Right-click and create a new boolean value
    and name its as extensions.checkCompatibility.19.0
    Set this value to false
    restart the browser
  • Make sure you update the objects properties 

Finally also be sure that you check different websites and objects!

Happy Coding...


Skillset - WebDriver Automation Engineer

Note: the Skillset category is just to gauge where you stand in terms of the skills required for the role

This is a full life cycle testing assignment for a Technical (Software) Test Analyst with experience automating Testing for Web applications using the Selenium WebDriver product. We need people that are comfortable coding their own scripts using Ruby, but if you’ve only used Java, here’s your chance to learn!

It’s an agile environment too using BDD and TDD techniques, so experience using cucumber, RSpec frameworks are used quite extensively here.

Because of the close and intimate working relationship with the stakeholders, candidates must have excellent English communication skills and be able to confidently refine requirements and collaborate with users to find solutions to difficult testing requirements.


Selenium WebDriver - launches firefox with IE tab options

So you are trying to do the most basic thing : launch firefox

Webdriver driver = new FirefoxDriver();

Firefox browser does open up, but in the foreground IETab+Options tool bar keeps popping up.

You repeat the steps manually and nothing!

How will you disable this add on so that a blank clean browser opens up in FF?

What you need to do is to launch your default profile when launching Firefox.

ProfilesIni profile = new ProfilesIni();

FirefoxProfile ffprofile = profile.getProfile("default");

WebDriver driver = new FirefoxDriver(ffprofile);

These generally require the following imports:

import org.openqa.selenium.firefox.FirefoxProfile;

import org.openqa.selenium.firefox.internal.ProfilesIni;

Happy Learning!

If this does not work then create a new profile , disble the addon IETab and save the profile
ProfilesIni profile = new ProfilesIni();

FirefoxProfile ffprofile = profile.getProfile("SeleniumProfile");

WebDriver driver = new FirefoxDriver(ffprofile);


Screenshots on VM with QTP

I am sure a lot of you have noticed that taking screenshots on a VM will result in a blank screen :)

The solution is that the machine should not be locked while running your scripts , similar to a solution provided in my earlier posts.If you missed that out here is the code:

Content of vbs File (keykaker):

' Keyboard activity faker
Set shell = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
interval = 180
key = "+"
output = True

' If running under WScript were not in a console so disable any output
If InStr(LCase(WScript.FullName), "wscript") > 0 Then output = False
' Handle the arguments
If args.Count > 0 Then
temp = args.Item(0)
If Not IsNumeric(temp) Then
WScript.Echo "Interval must be numeric"
WScript.Quit 1
ElseIf temp < 1 Then
WScript.Echo "Interval must be greater or equal to 1"
WScript.Quit 1
interval = temp
End If
End If
If args.Count = 2 Then
key = args.Item(1)
End If
' Output some blurb so the user knows what's happening
key_desc = key
If key = "+" Then key_desc = "Shift Key"
If key = "^" Then key_desc = "Ctrl Key"
If key = "%" Then key_desc = "Alt Key"
If output Then WScript.Echo "Key press faker started: Interval = "&interval&" seconds, Key = '"&key_desc&"'"
' Main loop, easy init?
While True
If output Then WScript.Echo "Faking keypress at " & Time
shell.SendKeys key
WScript.Sleep interval * 1000

TIP: As per the suggestion in the below link, instead of directly closing the remote session, executing the command “tscon.exe 0 /dest:console” on the remote machine to close the session, ensures that the remote console is still active, which will allow QTP to capture screenshot.


WebDriver java concepts - Private final static / public, default, protected, and private / Abstract / Interface / Final / Super / this

Continuing the WebDriver java concepts category here are a set of simple yet complex terminologies used in webdriver frameworks wrt Java:

Private final static attribute vs private final attribute -

Static means "associated with the class"; without it, the variable is associated with each instance of the class. If it's static, that means you'll have only one in memory; if not, you'll have one for each instance you create. static means the variable will remain in memory for as long as the class is loaded; without it, the variable can be gc'd when its instance is.
In general, static means "associated with the type itself, rather than an instance of the type."

That means you can reference a static variable without having ever created an instances of the type, and any code referring to the variable is referring to the exact same data. Compare this with an instance variable: in that case, there's one independent version of the variable per instance of the class. So for example:

Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);prints out 10: y.instanceVariable and x.instanceVariable are separate, because x and y refer to different objects.

You can refer to static members via references, although it's a bad idea to do so. If we did:
Test x = new Test();
Test y = new Test();
x.staticVariable = 10;
y.staticVariable = 20;
System.out.println(x.staticVariable);then that would print out 20 - there's only one variable, not one per instance. It would have been clearer to write this as:

Test x = new Test();
Test y = new Test();
Test.staticVariable = 10;
Test.staticVariable = 20;
System.out.println(Test.staticVariable);That makes the behaviour much more obvious. Modern IDEs will usually suggest changing the second listing into the third.

There is no reason to have a declaration such as
private final int NUMBER = 10;If it cannot change, there is no point having one copy per instance.

Difference between public, default, protected, and private?

Abstract Methods and Classes

  An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.
Note: All of the methods in an interface are implicitly abstract, so the abstract modifier is not used with interface methods (it could be—it's just not necessary).

What Is an Interface?

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:

interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {
// remainder of this class
// implemented as before

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Java Final Keyword

A java variable can be declared using the keyword final. Then the final variable can be assigned only once.

A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it.

Java classes declared as final cannot be extended. Restricting inheritance!

Methods declared as final cannot be overridden. In methods private is equal to final, but in variables it is not.

Java local classes can only reference local variables and parameters that are declared as final.

A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance 

 Super :
super keyword is used to call a superclass constructor and to call or access super class members(instance variables or methods).
syntax of super : super(arg-list)

When a subclass calls super() it is calling the constructor of its immediate superclass.
super() must always be the first statement executed inside a subclass constructor.
Here member can be either method or an instance variables.
This second form of super is most applicable to situation in which member names of a subclass hide member of superclass due to same name.

‘this’ is used for pointing the current class instance. It can be used with variables or methods. Look into the following example:

class Test{
private int i=10;
public void m(){

In the above code this is used for the current instance. Since this is instance of a class it cannot be used inside a static method.


Learn Selenium the right way

So most of my fellow testers and newbies to testing agree that learning selenium isn't all that easy especially if you have been using either QTP or any other tool that uses simple scripting (Compared to any scary code that has a lot of complex jargons)
To make things easier and less complicated for all of whose mails and messages I get on linked-in / facebook and the blog. I have chalked out a simple and strategic set of things to learn and If you go about this(I would say 15 day schedule) then you are ready for any god damn Selenium Code!

Of course we will choose Java as the language of choice:

Java Introduction and Concepts
  • First Java program
  • Concept of class file
  • Platform independence
  • Datatypes in Java
  • String class
  • If statements
  • While Loop
  • For Loops
  • Single/Two Dimensional Arrays
  • Function Input Parameters
  • Function Return Types
OOPS Concept's 
  • Local/ Global Variables
  • Static and Non-Static Variables
  • Static and Non-Static Functions
  • Objects in Java
  • Call by reference and Value
  • Constructors
  • Inheritance
  • Interface
  • Overloadings and Overriding Funtions
More Java
  • Packages
  • Access modifiers - Public, Private, Default, Protected
  • Exception hading with try catch block
  • Throwable Class
  • Final and Finally
  • Throw and Throws
  • Collections API
  • ArrayList Class
  • HashTable Class
  • Reflection API 
That's Enough Java already
  • String class and functions
  • Reading/Writing Text Files
  • Reading Properties File in Java
  • Concept of jar file
  • POI API in java
  • Reading/Writing Microsoft XLS Files
  • Log4j API for Logging
Junit or TestNG?
  • Configuring Junit 4 in Project/Eclipse
  • Junit 4 annotation
  • Running Test in Junit
  • Skipping Tests
  • Parameterizing Tests
  • Using Assertions
  • Reporting Errors / ErrorCollector
  • Batch Running - Custom Runners
  • OR
  • TestNg annotations
  • Running a Test in TestNg
  • Batch Running of tests in TestNg
  • Skipping Tests
  • parameterizing Tests - DataProvider
  • Assertions/Reporting Errors
  • TestNg Reports
  • XSLT report generation generation using TestNg and Ant
  • Building a BAT file to run tests using ANT
  • What is Ant
  • Downloading and configuring Ant
  • Build.xml configuration
  • HTML Report generation using Ant
Selenium WebDriver Demystified
  •  XPATHS and installing firebug to get XPATHS
  •  Wait Commands
  •  Verification and Assertions
  •  JavaScript
  •  Echo, StoreEval and StoredVars Demystified
  •  Reading XML from JavaScript using DOM.
  •  Handling JavaScript Alerts
  •  Configuring in eclipse
  •  Drivers for Firefox, IE, chrome, Iphone, Android etc
  •  Selenium RC and WebDriver
  •  Firefox profile
  •  Close and Quit -Difference
  •  Importing webdriver documentation in eclipse
  •  WebDriver Class
  •  Proxy settings with webdriver
  •  HTMLUnit driver
  •  Firepath and firebug Add-ons 
  •  Inspecting elements in Mozilla, Chrome and IE
  •  WebDriver Interface
  •  WebElement Interface
  •  Identifying WebElements using id, name, class 
  •  Xpaths 
  •  CssSelectors as compared to Xpaths
  •  Class attribute
Used to Selenium?
  •  Handling Dynamic objects/ids on the page
  •  Working with different browsers without changing code
  •  Managing Input fields, Buttons and creating custom xpaths
  •  Managing/Identifying Links with xpaths/css selectors
  •  Extracting More than one object from a page
  •  Extracting all links of a page/Bulk extraction of objects
  •  Extracting Objects from a specific area of a web page
  •  Finding response Headers/ response code
  •  Finding whether object is present on page or not
  •  Handling drop down list
  •  Select Class in Selenium API
  •  Managing radio buttons and Checkboxes
  •  Hidden components
  •  isDisplayed function
  •  Taking Screenshots of the web pages
  •  Implicit and Explicit waits
  •  PageLoadTimeout Property
  •  WebDriverWait Class
  •  WebDriver.Timeout Interface
  •  ExpectedCondition interface and ExpectedConditions class
  •  WaitUntil Condition
  •  Fluent Wait
  •  Managing Ajax based components
  •  Concepts of Set Interface in Java
  •  Window Handles
  •  Managing tabbed windows in IE, Chrome and Mozilla
  •  Managing popups in IE, Chrome and Mozilla
  •  Closing windows
  •  Default Popups
  •  Testing https websites / Managing certificate errors in https websites in IE, Chrome and Mozilla
  •  Dynamic WebTable Handling
  •  Attaching files with Selenium
  •  Mouse movement with Selenium- Mouse Interface
  •  Handling Ajax Autosuggests
  •  Handling Frames in Web Page
  •  Handling cookies
  •  Simulaing front and back buton click on Browser using selenium
  •  Assigning Firefox profile parameters
  •  Listeners- Using WebDriverEventListener
  •  Finding Coordinates of a Web Object
  •  Actions class in Webdriver
  •  Drag, drop, native events


Tabelize it - Create tables in blogger!

Trying to create tables in your blog posts , here is an easy way:

A quick tool for creating HTML tables out of spreadsheet data

WebDriver Java Concepts - HashMaps

So a lot of automation engineers I know have started to venture into the world of Selenium WebDriver. Looking at this I will now start a series of posts that will be tagged as "WebDriver Java Concepts". The intention will be to add concepts of Java and WebDriver that a newbie should learn.

To start with one of the most popular concepts that is used in Selenium frameworks:
HashMap - Hashmaps in simple terms are nothing but key value pairs just like the object dictionary that we have in QTP. A more technical definition would be that "The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets."

Points to ponder:
  • The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
  • The HashMap class supports four constructors.
    • The first form constructs a default hash map: HashMap( )
    • The second form initializes the hash map by using the elements of m: HashMap(Map m)
    • The third form initializes the capacity of the hash map to capacity: HashMap(int capacity)
    • The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments: HashMap(int capacity, float fillRatio)
  • An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed
  • You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.