lundi 8 février 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 :

@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 :

  • 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.

Aucun commentaire:

Enregistrer un commentaire