Getting Started with WebDriver (a Browser Automation Tool)
Posted At : May 17, 2010 11:08 AM | Posted By : Bob Silverberg
Related Categories: WebDriver
A few weeks ago during MXUnit Office Hours, Bill Shelton demonstrated using WebDriver to create functional tests in Java. It was a pretty cool demo and I meant to give it a whirl for a while, but only got around to doing it this weekend. I had to refer back to the recording of the session a number of times, so I thought it would be worthwhile to document the steps to get a project up and running in Eclipse that uses WebDriver. Let's start with some background.
What is WebDriver?
WebDriver is a tool that allows you to write code, in a number of languages, that automates a browser and allows you to interrogate what is rendered by the browser. You can use these features to created automated tests of a web application. You may be familiar with a tool called Selenium, which does similar things, but works within the context of a web browser itself. The Selenium project and the WebDriver project are merging to create Selenium 2.0. That project is a work in progress, but there's nothing to stop you from experimenting with WebDriver right now.
For a bit more of an official definition, here's some info from the Selenium 2.0 and WebDriver page at SeleniumHQ:
WebDriver is a tool for automating testing web applications, and in particular to verify that they work as expected. It aims to provide a friendly API that's easy to explore and understand, which will help make your tests easier to read and maintain. It's not tied to any particular test framework, so it can be used equally well with JUnit, TestNG or from a plain old "main" method.
WebDriver uses a different underlying framework from Selenium's javascript Selenium-Core. It also provides an alternative API with functionality not supported in Selenium-RC. WebDriver does not depend on a javascript core embedded within the browser, therefore it is able to avoid some long-running Selenium limitations.
WebDriver's goal is to provide an API that establishes
- A well-designed standard programming interface for web-app testing.
- Improved consistency between browsers.
- Additional functionality addressing testing problems not well-supported in Selenium 1.0.
I hope to write a number of posts about working with WebDriver. This first post will be a quick guide to setting up an Eclipse project and getting WebDriver to interact with a web page. Let's get started.
Create a Java Project
We're going to be writing Java code to drive WebDriver, so the first thing we need is a new Java project. Before starting this investigation I had written a grand total of 0 lines of Java code in Eclipse, so I didn't have a clue where to start. Luckily, as I mentioned in the opening, Bill demonstrated all of the steps for us in his presentation during MXUnit Office Hours, so I was able to just copy his steps.
- Open Eclipse (or CFBuilder, which I'm sure you know is Eclipse).
- From the menu choose File, New, Project...
- In the folder Java, choose Java Project.
- Give your project a name, accept the rest of the defaults, and click Next.
- Accept the defaults and click Finish.
Add the WebDriver jar files to your project
Next we need to add the jar files that are required by WebDriver to our project. We'll start by downloading them.
- Go to the Selenium Google Code Page
- From the sidebar labelled Featured downloads, choose the Selenium Java zip. As of this writing the file is called selenium-java-2.0a4.zip. That will take you to the page for the download itself.
- Click on the filename to download the zip to your machine.
- Unzip the files into the project that you just created. Bill suggested creating a folder under the project root called /lib, and then a folder underneath that called selenium-jars and placing the files there.
- Back in Eclipse, right click on your project in the Package Explorer and choose Build Path, Configure Build Path....
- Choose the Libraries tab, if it isn't already selected.
- Click Add Jars...
- Select all of the jars that you just unzipped into the /lib/selenium-jars/ folder and click OK. Your Java Build Path dialog should look something like this:
- Choose the primary selenium jar, which in this example is selenium-java-2.0a4.jar, click the down triangle and double-click on Javadoc location. Adding a Javadoc location will add help information to code assist.
- Enter the location for the Selenium JavaDocs into the Javadoc location path field. The current location is http://selenium.googlecode.com/svn/trunk/docs/api/java/.
- Click OK and then OK again. Your project is now ready to use the WebDriver API.
Add a class that uses WebDriver
In this next step I'm going to depart from Bill's presentation and show you how to create a standalone Java project that uses WebDriver. Bill showed us how to create a JUnit test that uses WebDriver, and that is probably what you're going to want to do to create an actual functional test, but to keep things simple let's just try to get WebDriver to do something. In the next post I'll go over creating a JUnit test.
- Right click on the /src folder in your project and choose New, Package.
- Give the package a name and click Finish.
- Right click on the package and choose New, Class.
- Give the class a name and accept the other defaults, but make sure that public static void main(String[] args) is checked under Which method stubs would you like to create? Click Finish.
You should end up in an editor window for your new class that contains code similar to this:
2
3public class Test {
4
5 /**
6 * @param args
7 */
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10
11 }
12
13}
Edit your code so it looks like this:
2
3import org.openqa.selenium.By;
4import org.openqa.selenium.WebDriver;
5import org.openqa.selenium.WebElement;
6import org.openqa.selenium.htmlunit.HtmlUnitDriver;
7
8public class Test {
9
10 public static void main(String[] args) {
11 WebDriver driver = new FirefoxDriver();
12 driver.get("http://www.google.com");
13 WebElement element = driver.findElement(By.name("q"));
14 element.sendKeys("MXUnit");
15 element.submit();
16 }
17
18}
Run it!
Press shift+command+F11 to run your Java project. You should see a Firefox browser start up, navigate to www.google.com, enter the text MXUnit into the search field, and submit the form, so you end up looking at the MXUnit search results. This worked on my system, and hopefully it will work on yours. I'm quite new to all of this, but I did see mentions of issues with different installations of Firefox, and, of course, you must have Firefox installed in order for this to work.
I'm not going to explain what any of the code above is doing, but it should be pretty easy to interpret. I will go into more details in a future blog post, but I think this post has now covered what I wanted to cover, which is how to get WebDriver up and running in Eclipse. As I mentioned above, the next post will be about writing a JUnit test that uses WebDriver so we can do some actual functional testing with it.
Once again I'd like to mention that all of this info was gleaned from Bill Shelton's presentation during MXUnit Office Hours, which run every other Monday from noon to 1pm Eastern time. I encourage anyone and everyone to join us at experts.na3.acrobat.com/mxunit-office-hours/.
Have you seen Badboy (http://www.badboysoftware.biz/)?
It does something similar but uses a graphical interface. Badboy is very easy to use (actually darned simple - just open up BB, navigate through the site or test case and that's it).
Badboy is also scriptable, using jScript. The chief downside to it that you have to have IE on your machine.
I use it to develop test cases etc. One thing that makes it very useful is that you can export your badboy saved files to use as jMeter load testing xml configuration file.
Currently I use it to automate a download data files from a site that uses password protection.
regards,
larry
Hey, one minor point (and it was my shortcomming) ... the URL for the Javadoc should omit the 'index.html' and be : http://selenium.googlecode.com/svn/trunk/docs/api/... . Eclipse still says the location "might be valid" or some such.
-bill
Larry, thanks for the info to Badboy! This might be a winner for one particular Win32/IE project I'm working on. Though not open source, it appears to be quite reasonable at 45USD or less.
-bill
and configure a Remote Server?
When I run this test I get A NoSuchElementFoundException. Th
The google.com website is not even been requested.
Please let me know what extra configuration is required.
Thanks in advance
I wrote a webdriver script which will do some update
on UI and then it needs to verify the oracle datadase to
check whether the update is successful or not in a
particular DB table . How can I check
the DB part using webdriver .
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
FirefoxDriver cannot be resolved to a type
at test.test.main(test.java:11)
what is the problem ??
import org.openqa.selenium.firefox.FirefoxDriver;
WebDriver driver = new InternetExplorerDriver();
Of course you have to import the corresponding library...
Tried chrome driver but it just kills the CPU, consumes too much resources...
I know selenium 2 with web driver is ready now, but their documentation sucks... Yesterday I tried every possible way to make it work on windows 7 but it was impossible, the maven connection never worked for me and the tutorial they have just tells you to get Maven information somewhere else...
I canĀ“t believe someone releases a tool with such a crappy documentation for the developers!
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot instantiate the type WebDriver
at test.Test.main(Test.java:11)
could you provide more details on the error? Initially it look like missing references.
Do you have some documentation on how to create a build file using ant or maven?
Kudos!!!
import org.openqa.selenium.firefox.FirefoxDriver;
as posted by Bill Mackie.
Many thanks!
"Protected mode (enable or disable)". Not sure what it is
This was pretty good piece of information.
What amaze me is the leverage of power of Java into test Automation.
I had been working around for 2 days just to evoke "FirefoxWebDriver" class. And I guess I was missing somewhere.
I came across this blog and my problem got resolved.
I am QTP professional and my interest is inclined towards Java.
I'll be happy to know if have all the features of QTP.
Thank you once again and keep writing.
i've followed all the instructions and added the:
import org.openqa.selenium.firefox.FirefoxDriver;
but i'm getting the following message:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function
at webdriverpackage.Test.main(Test.java:12)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
i'm a total novice so any help would be greatly appreciated
its working now and ran successfully
Thanks!
Bill Mackie's above comment regarding adding the import "import org.openqa.selenium.firefox.FirefoxDriver;" should be added in, seems like it doesn't work without that.
Also might be helpful to note that if someone simply copies and pastes your code (as I did), the line numbers must be removed before it will work.
~Chaitanya
Your blog helped me solve the path to java doc identifying problem, its now all setup correctly and I am not seeing any errors
But I am trying to automate using IE webdriver and when I run following code on eclipse I am getting error
package webtest2;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class thirdprogram {
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer_x64_2.35.3\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.close();
driver.quit();
}
}
Started InternetExplorerDriver server (64-bit)
2.35.3.0
Listening on port 13277
Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Could not get document from window handle (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 8.89 seconds
Build info: version: '2.37.0', revision: 'a7c61cb', time: '2013-10-18 17:15:02'
System info: host: 'PRADEEPM-PC', ip: '192.168.2.173', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_45'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:151)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:216)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:201)
at org.openqa.selenium.ie.InternetExplorerDriver.run(InternetExplorerDriver.java:224)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:214)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:180)
at webtest2.thirdprogram.main(thirdprogram.java:13)
thanks