Tuesday, 8 January 2013

Spring Selenium Tests With Annotations

This post describes how to implement Selenium tests in Java. It is inspired from the post by Alex Collins, with annotations. The code is available on GitHub in the Spring-Selenium-Test directory. Some alternative and much lighter techniques are available to unit test a Spring MVC application. To unit test services, see here.

Page, Configuration & Controller

We create a simple page with 'Hello World':
<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <title>Welcome !!!</title>
   Hello World !
We keep our controller very simple:
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        return resolver;

and our controller too:
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";


For Selenium Testing

We create a configuration for testing. It provides the URL to open the application locally. The application is opened with Firefox:
public class TestConfig {

    public URI getSiteBase() throws URISyntaxException {
        return new URI("http://localhost:10001/spring-selenium-test-1.0.0");

    public FirefoxDriver getDrv() {
        return new FirefoxDriver();

We also define an abstract class as a basis for all tests. It automatically closes Firefox after the test:
@ContextConfiguration(classes={ TestConfig.class })
public abstract class AbstractTestIT {

    protected URI siteBase;

    protected WebDriver drv;

        Runtime.getRuntime().addShutdownHook(new Thread() {
           public void run() {

And we implement a selenium test where we make sure our page contains 'Hello World':
public class SeleniumTestIT extends AbstractTestIT {

    public void testWeSeeHelloWorld() {
        assertTrue(drv.getPageSource().contains("Hello World"));

The maven dependencies are the same as those described in Alex Collins's post.

Building The Application

If you build the application, it will open and close firefox automatically. The test will be successful.