7

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

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

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

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

4

1 回答 1

2

对于集成测试,您可以像我一样使用 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);
}
于 2013-02-27T12:36:11.080 回答