Home Ask Login Register

Developers Planet

Your answer is one click away!

JulienCsj February 2016

Test POST request on PlayFramework 2.4.x

Good morning,

I'm trying to test some POST requests on my controllers.

I have no problems with GET request :

public void testGetAll() {
    TestModel test = new TestModel();
    test.done = true;
    test.name = "Pierre";

    TestModel test2 = new TestModel();
    test2.done = true;
    test2.name = "Paul";

    Result result = new controllers.ressources.TestRessource().get(null);
    assertEquals(200, result.status());
    assertEquals("text/plain", result.contentType());
    assertEquals("utf-8", result.charset());

But when I have to test a POST request, i can't give POST params to the controller.

here is the method I want to test :

public Result post() {
    Map<String, String> params =     RequestUtils.convertRequestForJsonDecode(request().queryString());

    T model = Json.fromJson(Json.toJson(params), genericType);

    return ok(Json.prettyPrint(Json.toJson(reponse)));

I've try several solutions, but I can't find a proper one :

  • Try to use FakeRequest
  • Try to Mock the Http.Request object

So, what is the best way to write tests for my controllers ?

I'm using Play Framework 2.4.6 with Java. Junit 4 and Mockito.


Kris February 2016

For tests of an POST action I use the RequestBuilder and the play.test.Helpers.route method.

For one with JSON data it could look like this (I use Jackson's ObjectMapper for marshaling):

public class MyTests {

  protected Application application;

  public void startApp() throws Exception {
    ClassLoader classLoader = FakeApplication.class.getClassLoader();
    application = new GuiceApplicationBuilder().in(classLoader)

  public void myPostActionTest() throws Exception {

    JsonNode jsonNode = (new ObjectMapper()).readTree("{ \"someName\": \"sameValue\" }");
    RequestBuilder request = new RequestBuilder().method("POST")
    Result result = route(request);


  public void stopApp() throws Exception {

Post Status

Asked in February 2016
Viewed 3,287 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life