JulienCsj
JulienCsj

Reputation: 368

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 :

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

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

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

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);
    model.save();

    reponse.setData(model);
    return ok(Json.prettyPrint(Json.toJson(reponse)));
}

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

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.

Upvotes: 1

Views: 3574

Answers (1)

Kris
Kris

Reputation: 4823

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;

  @Before
  public void startApp() throws Exception {
    ClassLoader classLoader = FakeApplication.class.getClassLoader();
    application = new GuiceApplicationBuilder().in(classLoader)
            .in(Mode.TEST).build();
    Helpers.start(application);
  }

  @Test
  public void myPostActionTest() throws Exception {

    JsonNode jsonNode = (new ObjectMapper()).readTree("{ \"someName\": \"sameValue\" }");
    RequestBuilder request = new RequestBuilder().method("POST")
            .bodyJson(jsonNode)
            .uri(controllers.routes.MyController.myAction().url());
    Result result = route(request);

    assertThat(result.status()).isEqualTo(OK);
  }

  @After
  public void stopApp() throws Exception {
    Helpers.stop(application);
  }
}

Upvotes: 3

Related Questions