Skip to content
javahacks.dev
Play Framework

How to Test Play Applications With JUnit and Fake Requests

Test a Play application with JUnit, from plain controller unit tests to full-application tests that route fake HTTP requests and use an embedded server.

6 min read
Summarize in AI
Flat illustration of a real object swapped for a mock on strings, with the JUnit5, Spring Boot, GitHub Actions and OpenJDK logos.

Play is easy to test once the layers are kept apart. A service class gets a unit test, a controller gets a request routed through the real router, and a handful of flows get a test against a running server. This guide builds all three on Play 3.0 with JUnit, in that order, and ends on how to run them. The reasoning behind the split is in a practical Java testing strategy, and the JUnit basics are in the JUnit 5 tutorial.

Layer 1: unit test the service

test/services/PricingTest.javajava
class PricingTest {

    @Test
    void appliesTenPercentOverThreshold() {
        assertEquals(9_000, new Pricing().total(10_000));
    }
}

No Play, no application, no injector, and it runs in milliseconds. The goal is to push as much logic as possible into classes that look like this one. A controller that only parses the request, calls a service and renders a result needs very little testing of its own, and the tests it does need belong in layer 2.

Layer 2: route a fake request

WithApplication is a base class that starts the application before each test and stops it afterwards.

test/controllers/ProductControllerTest.javajava
import static org.junit.Assert.assertEquals;
import static play.mvc.Http.Status.OK;
import static play.test.Helpers.*;

import org.junit.Test;
import play.mvc.Http;
import play.mvc.Result;
import play.test.WithApplication;

public class ProductControllerTest extends WithApplication {

    @Test
    public void listsProducts() {
        Http.RequestBuilder request = new Http.RequestBuilder()
                .method(GET)
                .uri("/api/products");

        Result result = route(app, request);

        assertEquals(OK, result.status());
        assertEquals("application/json", result.contentType().orElse(""));
    }
}

route sends the request through the router, the filters and the action, exactly as production does, with no network in between. It returns a Result, and contentAsString(result) reads the body. Note the imports: WithApplication uses JUnit 4 annotations (org.junit.Test), so the JUnit 4 engine (Vintage) must be on the test classpath next to Jupiter unless your Play version ships a JUnit 5 base class. The migration path is in JUnit 4 to 5.

Post a JSON body and fake a session

java
Http.RequestBuilder request = new Http.RequestBuilder()
        .method(POST)
        .uri("/api/products")
        .session("user", "ana")
        .bodyJson(Json.newObject().put("name", "Grinder").put("priceCents", 8900));

Result result = route(app, request);
assertEquals(CREATED, result.status());

bodyJson sets the content type and the body together. .session("user", "ana") stands in for a login, so a controller guarded by an action that reads the session sees an authenticated user without a login round trip. Add one test for the unauthenticated case too, expecting 401 or a redirect, because a guard that is never exercised in the negative is untested.

Replace dependencies per test

Override provideApplication to change configuration or swap bindings for one test class.

java
@Override
protected Application provideApplication() {
    return new GuiceApplicationBuilder()
            .configure("db.default.url", "jdbc:h2:mem:test")
            .overrides(bind(PaymentGateway.class).to(FakeGateway.class))
            .build();
}

FakeGateway replaces the real client in dependency injection, so no mocking framework is needed for the common case. A hand-written fake with a list of recorded calls is easier to read than stubbing, and the difference between the two is covered in test doubles.

The database is the one dependency to be careful with. H2 in memory starts instantly but accepts SQL that PostgreSQL rejects and the reverse. If production runs PostgreSQL, run the controller tests against a Testcontainers PostgreSQL, a point argued in what to mock and what to leave real.

Layer 3: a running server

java
public class ApiServerTest extends WithServer {

    @Test
    public void healthEndpointResponds() throws Exception {
        try (WSTestClient client = WSTestClient.newClient(providePort())) {
            WSResponse response = client.url("/health").get().toCompletableFuture().get();
            assertEquals(200, response.getStatus());
        }
    }
}

WithServer starts a real HTTP server on a random free port, and WSTestClient calls it over a socket. This layer covers what route cannot: the network stack, CORS and compression filters, and request body size limits. Because each test boots the framework, keep these to a few smoke checks per service.

Run them

Shell
sbt test
sbt "testOnly controllers.ProductControllerTest"

testOnly takes a class pattern, which keeps the loop short while you work on one controller. In CI, run the whole suite once and publish the XML from target/test-reports.

Keep the suite fast

Booting the application for every test method is the cost that decides whether this suite stays pleasant. A WithApplication test starts the injector, loads configuration, and runs any eagerly bound modules, which commonly takes one to three seconds on a mid-sized project. Ten controller classes with eight methods each is a few minutes of start-up alone. Three habits keep it in check.

Group assertions about one endpoint into a single test method where the setup is expensive, rather than starting the application for each assertion. Bind heavyweight dependencies lazily so tests that never touch them do not pay for them. And tag the WithServer tests so they run in a separate pass, because they are the slowest and fail for infrastructure reasons more often than the rest.

If a controller test needs data, create it through the application's own repository inside the test, not through a shared SQL script. Shared scripts couple tests to each other: a change to one fixture row breaks tests that never mention it. A test that creates exactly the rows it asserts on can run in any order and in parallel with others that use different keys.

What to assert on a result

result.status() is the obvious assertion and the least informative. Check the headers a client depends on: Content-Type, Location after a 201, and cache headers on a read endpoint. Parse the JSON body with Json.parse(contentAsString(result)) and assert on named fields, not on the whole string, so a new optional field does not break unrelated tests. For error paths, assert the status and the error body's code field together, since a test that only sees 400 cannot tell a validation error from a parsing one.

A note on the Play version

Play 3.0 moved from Akka to Apache Pekko, so imports such as akka.stream.Materializer in older test code become org.apache.pekko.stream.Materializer. Tests that only use Helpers, route and Http.RequestBuilder need no change, which is one more reason to prefer those helpers over reaching into the actor system. The move itself is walked through in Play 3 and Pekko.

Running the suite in CI

In a pipeline, run sbt test once with the default settings and publish the XML reports from target/test-reports. Cache the sbt and Ivy directories between runs, because dependency resolution dominates a cold build. Keep the WithServer tests in a second stage if they need ports, since parallel agents on one host can collide on a fixed port. A random port, as in the example, avoids the clash.

What these tests do not catch

The fake-request layer also misses anything that depends on the real clock, so freeze time through a bound Clock when an endpoint stamps results.

Browser behaviour needs a browser tool, and Play offers WithBrowser for Selenium; Playwright is the more common choice in newer projects. Twirl templates are covered indirectly by route, because the rendered body comes back in the result, but a visual regression needs screenshots. For Scala code, ScalaTest Plus Play offers equivalent helpers. The Java test chapter and the functional testing chapter of the Play manual list every helper.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.