Thursday, January 26, 2012

Getting Started with Webdriver (Java + Eclipse)


WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application. More info here.

Eclipse installation

  1. Download Eclipse (I use Eclipse Classic - don't really know what is the difference between all of them)
  2. Extract the archive to a folder (e.g. c:\eclipse)
  3. Run Eclipse.exe (I would recommend to create a shortcut and put it to the desktop or taskbar)
  4. Create a new Java Project - File/Add/Java Project. Name the project (e.g. webdriver) and accept the rest of the defaults

Webdriver setup

  1. Download the latest selenium-java-<newest version>.zip here
  2. Unzip the files into the project that you just created. I would suggest to create a folder under the project root called /lib (my example: c:\workspace\webdriver\lib\)
  3. Back in Eclipse, right click on your project in the Package Explorer and choose Properties -> Java Build Path
  4. Choose the Libraries tab and click Add External Jars...
  5. Select all the jars that you just unzipped into the /lib/ folder and click OK

Create a new test with Webdriver

  1. Add a new Package - File/New/Package (name it e.g. test)
  2. Select a new package and add a new class - File/New/Class. Give the class name (e.g. Test) and accept the other defaults, but make sure that public static void main(String[] args) checkbox is enabled. 
  3. Copy the following code into your Eclipse project and Run the test!


package test;

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

public class Test {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("webdriver how to find elements");
        element.submit();
        System.out.println("Test passed!");
    }

}


As the result Google page should be opened in new FireFox window. The code in Eclipse should look like this:

No comments:

Post a Comment