如何使用 Java 在 Play Framework 2.0 中测试文件上传的多部分表单数据请求?

2024-03-08

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

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

但似乎没有办法使用 Java 来做到这一点,因为 FakeRequests 的 withFormUrlEncodedBody 方法只支持字符串值?

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


对于集成测试,您可以像我一样使用 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Java 在 Play Framework 2.0 中测试文件上传的多部分表单数据请求? 的相关文章

随机推荐