0中测试多部分表单数据请求以上传文件

0中测试多部分表单数据请求以上传文件

本文介绍了如何使用Java在Play Framework 2.0中测试多部分表单数据请求以上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解您可以按照以下建议使用Scala API进行此操作:

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

但是似乎无法使用Java做到这一点,因为FakeRequests的withFormUrlEncodedBody方法仅支持字符串值?

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

这是API中缺少的功能还是有任何解决方法? (仅使用Java).

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

推荐答案

对于集成测试,您可以像我一样使用apache DefaultHttpCLient:

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);
}

这篇关于如何使用Java在Play Framework 2.0中测试多部分表单数据请求以上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:29