Creating and running a simple Selenium WebDriver test

15. September 2011 - Jani Palsamäki

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:

package com.yourcompany.selenium.yourclientprojectname;

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.

Next post

Meet us at DrupalCon London

Read More »

Comments

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?

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

Jani Palsamäki's picture

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.

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)

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!

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 ?

Jani Palsamäki's picture

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.

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.

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.

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.

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!!!

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

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.

16. February 2012 - 14:07 - Andy (not verified)

Hi, is it possible to get reports from maven selenium webdriver?

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

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!

Add new comment