【问题标题】: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
【问题描述】:
【问题讨论】:
标签:
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);
}