【问题标题】:How do I test multipart form data requests for file uploads in Play Framework 2.0 using Java?如何使用 Java 在 Play Framework 2.0 中测试文件上传的多部分表单数据请求?
【发布时间】:2012-10-19 09:10:51
【问题描述】:

我知道您可以按照此处的建议使用 Scala API 执行此操作:

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

但似乎没有办法使用 Java 执行此操作,因为 FakeRequests 的 withFormUrlEncodedBody 方法仅支持字符串值?

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

【问题讨论】:

  • 也在寻找有关如何执行此操作的示例。

标签: java playframework playframework-2.0 functional-testing


【解决方案1】:

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

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

这要求您在测试中启动服务器:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多