Tuesday, March 05, 2013

Getting started with WebDriver (Selenium 2)

WebDriver is a automation testing tool for automating testing web applications. It provides tester friendly API which is easy to explore and understand. This tool is not tied to any particular framework such as JUnit or TestNG. It can be used with simple "main" method or any of the unit testing framework such as JUnit or TestNG.

Required downloads: 
  • Download from here the latest version of selenium-server-standalone-x.y.z.jar where x, y and z are digits specifying the version of jar while created by the developers. 
  • Download respective drivers for your browser. Such as FirefoxDriver for Firefox, ChromeDriver for Chrome, InternetExplorerDriver for Internet Explorer and so on.
Quick steps: 
  1. Create a new java project in your favorite IDE 
  2. Add the downloaded jar file into your project build-path. 
  3. Make sure the browser you are selecting to run is installed in your machine.
  4. Copy and paste the following example to execute your first example on WebDriver.
Example Test:

In my example below i have chosen Firefox browser. Here i have not used any framework to execute my test, i have used simple "main" method to execute. The example is self explanatory by its comments.


package com.example.tests;

import java.util.concurrent.TimeUnit;

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

public class GoogleTest {

 public static void main(String[] args) {

  // I have chosen Firefox browser to execute my script
  WebDriver driver = new FirefoxDriver();

  // Go to the Google home page
  driver.get("https://www.google.co.in/");
  
  // Maximize the browser window
  driver.manage().window().maximize();

  // Enter the query string "Cheese"
  WebElement query = driver.findElement(By.name("q"));

  // Type 'aksahu blog' in the search field
  query.sendKeys("aksahu blog");
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

  // Click on the 'A. K. Sahu's Blog' link
  WebElement blog = driver.findElement(By.linkText("A. K. Sahu's Blog"));
  blog.click();
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

  // Quit the browser
  driver.quit();
 }
}