如何测试文件上传播放Framework 2.0中使用Java多形式的数据的请求?(How do I

2019-09-24 07:45发布

据我所知,这里建议你可以做到这一点使用Scala的API:

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

但是,似乎没有因为只有字符串值在FakeRequests' withFormUrlEncodedBody方法做支持使用Java这样的方式?

这是一个功能缺失的API或有什么解决方法吗? (仅使用的Java)。

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


文章来源: How do I test multipart form data requests for file uploads in Play Framework 2.0 using Java?