Documentation

You are viewing the documentation for the 2.4.0-M3 development release. The latest stable release series is 3.0.x.

§Writing functional tests

Play provides a number of classes and convenience methods that assist with functional testing. Most of these can be found either in the play.test package or in the Helpers class.

You can add these methods and classes by importing the following:

import play.test.*;
import static play.test.Helpers.*;

§FakeApplication

Play frequently requires a running Application as context: it is usually provided from play.Play.application().

To provide an environment for tests, Play provides a FakeApplication class which can be configured with a different Global object, additional configuration, or even additional plugins.

Application fakeApp = Helpers.fakeApplication();

Application fakeAppWithGlobal = fakeApplication(new GlobalSettings() {
  @Override
  public void onStart(Application app) {
    System.out.println("Starting FakeApplication");
  }
});

Application fakeAppWithMemoryDb = fakeApplication(inMemoryDatabase("test"));

If you’re using Guice for dependency injection then an Application for testing can be built directly, instead of using FakeApplication.

§Testing with a fake application

To run tests with an Application, you can do the following:

@Test
public void findById() {
    running(fakeApplication(inMemoryDatabase("test")), () -> {
        Computer macintosh = Computer.findById(21l);
        assertEquals("Macintosh", macintosh.name);
        assertEquals("1984-01-24", formatted(macintosh.introduced));
    });
}

You can also extend WithApplication, this will automatically ensure that an application is started and stopped for you:

public class FunctionalTest extends WithApplication {

§Testing with a server

Sometimes you want to test the real HTTP stack from with your test. You can do this by starting a test server:

@Test
public void testInServer() {
    running(testServer(3333), () -> {
        assertEquals(OK, WS.url("http://localhost:3333").get().get(timeout).getStatus());
    });
}

§Testing with a browser

If you want to test your application from with a Web browser, you can use Selenium WebDriver. Play will start the WebDriver for you, and wrap it in the convenient API provided by FluentLenium.

@Test
public void runInBrowser() {
    running(testServer(), HTMLUNIT, browser -> {
        browser.goTo("/");
        assertEquals("Welcome to Play!", browser.$("#title").getText());
        browser.$("a").click();
        assertEquals("/login", browser.url());
    });
}

§Testing the router

Instead of calling the Action yourself, you can let the Router do it:

@Test
public void testBadRoute() {
    Result result = route(fakeRequest(GET, "/xx/Kiki"));
    assertEquals(NOT_FOUND, result.status());
}

Next: Testing with Guice