Java PlayFramework 2.4.x上的测试POST请求

Java PlayFramework 2.4.x上的测试POST请求,java,testing,playframework,Java,Testing,Playframework,早上好 我正在尝试在我的控制器上测试一些POST请求 我对GET请求没有任何问题: @Test public void testGetAll() { TestModel test = new TestModel(); test.done = true; test.name = "Pierre"; test.save(); TestModel test2 = new TestModel(); test2.done = true; test2

早上好

我正在尝试在我的控制器上测试一些POST请求

我对GET请求没有任何问题:

@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"));
}
但是当我必须测试POST请求时,我不能向控制器提供POST参数

以下是我要测试的方法:

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)));
}
public Result post(){
Map params=RequestUtils.convertRequestForJsonDecode(request().queryString());
T model=Json.fromJson(Json.toJson(params),genericType);
model.save();
响应。设置数据(模型);
返回ok(Json.prettyPrint(Json.toJson(reponse));
}
我尝试了几种解决方案,但找不到合适的:

  • 试着用假货
  • 尝试模拟Http.Request对象
那么,为我的控制器编写测试的最佳方法是什么

我在Java中使用PlayFramework2.4.6。
Junit 4和Mockito。

对于POST操作的测试,我使用RequestBuilder和play.test.Helpers.route方法

对于一个使用JSON数据的示例,它可能如下所示(我使用Jackson的ObjectMapper进行封送处理):


谢谢你,克里斯。不幸的是,参数从未传递给控制器。我尝试过许多方法(RequestBuilder、Helpers.invokeWithContext),但问题总是一样的。@JulienCsj:在进行实际测试之前是否启动应用程序?我用一个假的应用程序和一个GuiceApplicationBuilder更新了我的代码,就像用于Play2.4一样。
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);
  }
}