I understand that you can do this using the Scala API as suggested here:
https://groups.google.com/forum/?fromgroups=#!topic/play-framework/1vNGW-lPi9I
But there seems to be no way of doing this using Java as only string values are supported in FakeRequests' withFormUrlEncodedBody method?
Is this a missing feature in the API or is there any workaround? (Using only Java).
Class MultipartRequest. A utility class to handle multipart/form-data requests, the kind of requests that support file uploads. This class emulates the interface of HttpServletRequest , making it familiar to use. It uses a "push" model where any incoming files are read and saved directly to disk in the constructor.
Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.
Multipart upload allows you to upload a single object as a set of parts. Each part is a contiguous portion of the object's data. You can upload these object parts independently and in any order. If transmission of any part fails, you can retransmit that part without affecting other parts.
Uploading files in a form using multipart/form-data The standard way to upload files in a web application is to use a form with a special multipart/form-data encoding, which lets you mix standard form data with file attachment data. Note: The HTTP method used to submit the form must be POST (not GET ).
For integration testing you can use apache DefaultHttpCLient like I do:
@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);
}
This requires that you start a server in your tests:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With