How do I test multipart form data requests for file uploads in Play Framework 2.0 using Java?

情到浓时终转凉″ 提交于 2019-12-12 10:38:09

问题


I understand that you can do this using the Scala API as suggested here:

https://groups.google.com/forum/?fromgroups=#!topic/play-framework/1vNGW-lPi9I

But there seems to be no way of doing this using Java as only string values are supported in FakeRequests' withFormUrlEncodedBody method?

Is this a missing feature in the API or is there any workaround? (Using only Java).


回答1:


For integration testing you can use apache DefaultHttpCLient like I do:

@Test
public void addFileItem() throws Exception {
    File testFile = File.createTempFile("test","xml");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost method = new HttpPost(URL_HOST + "/api/v1/items/file");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("description", new StringBody("This is my file",Charset.forName("UTF-8")));
    entity.addPart(Constants.ITEMTYPE_KEY, new StringBody("FILE", Charset.forName("UTF-8")));
    FileBody fileBody = new FileBody(testFile);
    entity.addPart("file", fileBody);
    method.setEntity(entity);

    HttpResponse response = httpclient.execute(method);             
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(CREATED);
}

This requires that you start a server in your tests:

public static FakeApplication app;
public static TestServer testServer;

@BeforeClass
public static void startApp() throws IOException {
    app = Helpers.fakeApplication();
    testServer = Helpers.testServer(PORT, app);
    Helpers.start(testServer);

}

@AfterClass
public static void stopApp() {
    Helpers.stop(testServer);
}


来源:https://stackoverflow.com/questions/12970953/how-do-i-test-multipart-form-data-requests-for-file-uploads-in-play-framework-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!