Getting started with WebDriver: A simple example


To start with, WebDriver is a tool that’s pretty useful in automating the testing of web apps. As of writing this post, Selenium, another popular and well established testing framework, integrated WebDriver API into Selenium v1 in its Selenium v2.x release.

If you’d like to read more about WebDriver and Selenium, click here.

What do you have to do to see WebDriver in action?
1. Download Selenium v2 Java Bindings (selenium-java-2.0b3.zip) from here.
2. Create a new Java Project in Eclipse IDE (say, SeleniumWebDriverTestProj).
3. Create a new folder under this project and name it libs (or whatever you think of).
4. Copy selenium-java-2.0b3.zip\selenium-2.0b3\selenium-java-2.0b3.jar to libs.
5. Copy all jars from selenium-java-2.0b3.zip\selenium-2.0b3\libs to libs directory.
6. Select all dependencies in libs, right-click on them, and select Build Path > Add to Build Path. Now, you can see some 26 jars added to Referenced Libraries.
7. Create a new class under src directory and name it as you like, say WebDriverTestClass. Add the below code to this class.


import java.io.File;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

//import org.openqa.selenium.htmlunit.HtmlUnitDriver;
//import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebDriverTestClass {
	public static void main(String a[]) throws InterruptedException {
		/*
		 * Firefox driver is cool, it supports javascript and offers a lot of
		 * features You can also use the below drivers WebDriver driver = new
		 * InternetExplorerDriver(); WebDriver driver = new HtmlUnitDriver();
		 */

		WebDriver driver = new FirefoxDriver();

		try {
			// Go to Google Home Page
			driver.get("http://www.google.com");

			// Look for search textbox and enter search term there
			WebElement searchBox = driver.findElement(By.name("q"));
			searchBox.sendKeys("WebDriver API");

			// Click on 'Search'
			WebElement searchButton = driver.findElement(By.name("btnG"));
			searchButton.click();

			// Not required or recommended any where, but just wait for the last
			// click()
			// operation to get completed fine
			Thread.sleep(2000);

			System.out.println("What's the current Url: "
					+ driver.getCurrentUrl());

			// if you wish to take screenshot of this page, you can!
			File scrFile = ((TakesScreenshot) driver)
					.getScreenshotAs(OutputType.FILE);
			FileUtils.copyFile(scrFile, new File(
					"c:\\screenshot\\googlesearch-webdriverapi.png"));

			// Close the driver, once you're done.
			driver.close();
		} catch (Exception e) {
			e.printStackTrace(); // For debugging purposes
		}

	}

}

That’s it. Our first example is complete.

About these ads

About this entry