In this blog post I will demonstrate how to write and run a simple test using Selenium WebDriver.
This example is written in Java, but WebDriver supports many other programming languages (C#, Python and Ruby).
Download and install Eclipse
Download and install Eclipse. I chose Eclipse IDE for Java EE Developers, but other distributions should work fine, too.
Apache Maven
Apache Maven should come pre-installed with Mac OS X Snow Leopard and Lion. You can test if you have Maven installed by typing the following command in terminal:
mvn -version
The output should be similar to following:
... Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200) Maven home: /usr/share/maven ...
I do not cover installation of Maven in this blog, but there are plenty of tutorials available for all supported operating systems.
Install m2eclipse
Eclipse does not have integrated Maven support out of the box. To add the support, I am going to use Maven Integration (m2e).
- In Eclipse: Help -> Install New Software…
- Type the following URL in field Work with: http://download.eclipse.org/technology/m2e/releases
- Click Add…
- Give a name for the repository (such as
m2eclipse) - Click OK
- Select the checkbox Maven Integration for Eclipse
- Click Next etc. to move forward and choose to restart Eclipse when prompted
Create a new Maven project
- In Eclipse: File -> New -> Other… -> Maven -> Maven project
- Click: Next, Next, Next
- Type in field Group Id:
com.yourcompany.selenium - Type in field Artifact Id:
yourclientprojectname - Click: Finish
Edit pom.xml
- Update JUnit version to 4.9:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency>
- Add Selenium dependency:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.6.0</version> </dependency>
- Eclipse should detect the pom.xml changes automatically, build the project and download required dependencies
- After the build is finished, there should be selenium*.jar files under Maven Dependencies under the Project Explorer pane
Cleaning up
- Delete example class called AppTest.java under src/test/java
Create a new test class
- Right-click over package com.yourcompany.selenium.yourclientprojectname under src/test/java and select New -> Class
- Type in field Name:
WhenSearchingForDrupalUsingGoogleTest - Click Finish
Implement the test class
Type or paste in the following code:
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WhenSearchingForDrupalUsingGoogleTest {
private String baseUrl;
private WebDriver driver;
private ScreenshotHelper screenshotHelper;
@Before
public void openBrowser() {
baseUrl = System.getProperty("webdriver.base.url");
driver = new FirefoxDriver();
driver.get(baseUrl);
screenshotHelper = new ScreenshotHelper();
}
@After
public void saveScreenshotAndCloseBrowser() throws IOException {
screenshotHelper.saveScreenshot("screenshot.png");
driver.quit();
}
@Test
public void pageTitleAfterSearchShouldBeginWithDrupal() throws IOException {
assertEquals("The page title should equal Google at the start of the test.", "Google", driver.getTitle());
WebElement searchField = driver.findElement(By.name("q"));
searchField.sendKeys("Drupal!");
searchField.submit();
assertTrue("The page title should start with the search string after the search.",
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("drupal!");
}
}));
}
private class ScreenshotHelper {
public void saveScreenshot(String screenshotFileName) throws IOException {
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File(screenshotFileName));
}
}
}
Run the test
- Using terminal, navigate to your project folder under your workspace folder
- Type in command:
mvn clean test -Dwebdriver.base.url=http://www.google.com
- You should see compilation messages and finally something resembling the following:
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.yourcompany.selenium.yourclientprojectname.WhenSearchingForDrupalUsingGoogleTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.679 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------
If everything went well, there should exist a file named screenshot.png at the root of your project folder. If there were errors, you can go and find more information under target/surefire-reports.

Comments
In this line: Permalink
20. September 2011 - 20:55 - DE (not verified)
In this line:
Edit pom.xml
Update JUnit version to 4.9
how would you go about Updating JUnit version to 4.9? On the pom.xml file?
Yes, by editing the pom.xml Permalink
23. September 2011 - 12:03 - Jani Palsamäki
Yes, by editing the pom.xml file. I modified the post to clarify this.
There are no tests to run Permalink
3. October 2011 - 22:41 - Ken Todd (not verified)
Thanks for this, but having issue. I get Build Success, but it says there are no tests to run:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -------------------------------------------------
[INFO] Total time: 4.953s
[INFO] Finished at: Mon Oct 03 12:39:19 MST 2011
[INFO] Final Memory: 20M/164M
Fixed errors in the code Permalink
5. October 2011 - 12:19 - Jani Palsamäki
Hi Ken,
Thanks for pointing this out.
After writing the original test class, I just renamed it in this blog. The name of the test class should have ended with Test.
I now renamed the class to WhenSearchingForDrupalUsingGoogleTest and fixed a blog post formatting error that erased one parameter type definition from the code (
<Boolean>).So, if you rename your class to WhenSearchingForDrupalUsingGoogleTest and use the updated code from this post, it should work as expected.
Maven test fail but unit test succeed Permalink
6. October 2011 - 14:39 - Maarten van Schelven (not verified)
When running the unit test everything succeeds
mvn clean test -Dwebdriver.base.url=http://www.google.com i get a error:
pageTitleAfterSearchShouldBeginWithDrupal(com.selenium.test.JunitWithSeleniumTest) Time elapsed: 0.109 sec <<< ERROR!
org.openqa.selenium.WebDriverException: Failed to connect to binary FirefoxBinary(C:\Program Files\Mozilla Firefox\firefox.exe) on port 7055; process output follows:
null
Build info: version: '2.6.0', revision: '13840', time: '2011-09-13 16:51:41'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.5.0_04'
Driver info: driver.version: FirefoxDriver
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:112)
I'm on OS X, so I can not Permalink
6. October 2011 - 15:32 - Jani Palsamäki
I'm on OS X, so I can not reproduce that exception. Some googling brought this up:
"Adding -Djava.net.preferIPv4Stack=true to process that executing the tests seems to workaround this issue."
http://code.google.com/p/selenium/issues/detail?id=645#c9
Hi Maarten, Permalink
19. January 2012 - 15:27 - Roozbeh (not verified)
Hi Maarten,
Did you find a solution to your problem? I am getting the same WebDriverException (in a different context) and I cannot seem to find a solution for it. There are many suggestions on the Web but none solving the issue.
Any help is appreciated!
I am using the code in the Permalink
21. October 2011 - 23:57 - Sundar (not verified)
I am using the code in the blog post (WhenSearchingForDrupalUsingGoogleTest), the build succeeds but still it says that
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
I am missing something ?
Sorry, I can not reproduce Permalink
24. October 2011 - 8:09 - Jani Palsamäki
Sorry, I can not reproduce that. Your problem might have something to do with Maven version or JUnit version. At least on Maven 3.0.3 and JUnit 4.9 the test runs just fine.
How do i run test in Eclipse? Permalink
24. October 2011 - 18:13 - JV (not verified)
How do i run test in Eclipse?
If I run the test using terminal it works fine but if I try run in eclipse (rus as>maven build) firefox opens but doesn't execute any of the commands, Google page doesn't come up.
You have to provide the URL argument via VM arguments Permalink
25. October 2011 - 8:55 - Jani Palsamäki
In Eclipse:
Run -> Run Configurations -> Arguments -> VM arguments-Dwebdriver.base.url=http://www.google.comWhich VM arguments Permalink
26. October 2011 - 21:00 - jv (not verified)
Now I'm getting an error running both in cmd prompt and eclipse. Below are the results i get. Any idea how to fix?
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.test.selenium.web.WhenSearchingForDrupalUsingGoogleTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 22.453 sec <<< F
AILURE!
Results :
Tests in error:
pageTitleAfterSearchShouldBeginWithDrupal(com.test.selenium.web.WhenSearchingF
orDrupalUsingGoogleTest): Timed out after 10 seconds
Build info: version: '2.6.0', revision: '13840', time: '2011-09-13 16:51:41'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.vers
ion: '1.7.0'
Driver info: driver.version: unknown
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18:15.347s
[INFO] Finished at: Wed Oct 26 12:54:59 CDT 2011
[INFO] Final Memory: 14M/34M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.
7.2:test (default-test) on project web: There are test failures.
I was able to run it once in Permalink
26. October 2011 - 21:27 - jv (not verified)
I was able to run it once in eclipse but not sure what happen next. I now get an error on both cmd prompt and eclipse. Result in cmd prompt are as follows:
Any ideas how to fix?
T E S T S
-------------------------------------------------------
Running com.test.selenium.web.WhenSearchingForDrupalUsingGoogleTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 17.219 sec <<< F
AILURE!
Results :
Tests in error:
pageTitleAfterSearchShouldBeginWithDrupal(com.test.selenium.web.WhenSearchingF
orDrupalUsingGoogleTest): Timed out after 10 seconds
Build info: version: '2.6.0', revision: '13840', time: '2011-09-13 16:51:41'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.vers
ion: '1.7.0'
Driver info: driver.version: unknown
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 19.437s
[INFO] Finished at: Wed Oct 26 13:21:52 CDT 2011
[INFO] Final Memory: 14M/34M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.
7.2:test (default-test) on project web: There are test failures.
Excellent Permalink
20. December 2011 - 22:30 - Shashi (not verified)
Superb blog it really a good start for someone who is very new to selenium automation. Keep up the good work!!!
selenium c# with webdriver Permalink
6. January 2012 - 8:17 - manasadesina (not verified)
Hello Jani,
This is Manasa working on Selenium C# with web driver.Can u provide me sample C# Web driver code for "How to retrieve data from excel sheet".
Please help me.
Thanks in advance.
Regards,
D.Manasa
Great post!! Permalink
9. January 2012 - 6:52 - Anoop (not verified)
Great post!!
Good one for new comers in Selenium 2 like me. I can able to run it from terminal as well as Eclipse with no issues.
Thanks for sharing your knowledge.
Reporting Permalink
16. February 2012 - 14:07 - Andy (not verified)
Hi, is it possible to get reports from maven selenium webdriver?
Start tests via eclipse Permalink
15. March 2012 - 12:32 - Daniel (not verified)
Hello,
is it possible to execute the tests from eclipse rather than from the command line?
Kind regards
Daniel
1/ To run in Eclipse, just Permalink
31. March 2012 - 18:15 - Anonymous (not verified)
1/ To run in Eclipse, just change
baseUrl = System.getProperty("webdriver.base.url");
to
baseUrl = "http://www.google.com";
Then, run the project as JUnit Test.
2/ If you change the searched keyword:
searchField.sendKeys("Drupal!"); => searchField.sendKeys("changed!");
then, remember to change:
return d.getTitle().toLowerCase().startsWith("drupal!");
to
return d.getTitle().toLowerCase().startsWith("changed!");
Thanks the author of this post!
How to use ant in maven3 to generate test report Permalink
17. April 2012 - 12:42 - AmyOrchid (not verified)
Seem to the subject. Thank you!
Add new comment