Mocking a multipart/form-data HTTP request in a unit test

If you have a servlet that processes HTML Form post data, you might want to simulate such a request in your unit tests. This is easily done with Apache Commons HttpClient using MultipartRequestEntity. This example uses MockHttpServletRequest from Spring, but can be easily modified for your needs in case you use another Servlet testing framework:

public void createMultipartFormDataRequest(MockHttpServletRequest request, String resourceName, String partName) throws IOException {
    // Load resource being uploaded
    byte[] fileContent = FileCopyUtils.copyToByteArray(
        getClass().getResourceAsStream(resourceName));
    // Create part & entity from resource
    Part[] parts = new Part[] {
        new FilePart(partName, new ByteArrayPartSource(resourceName, fileContent)) };
    MultipartRequestEntity multipartRequestEntity =
        new MultipartRequestEntity(parts, new PostMethod().getParams());
    // Serialize request body
    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(requestContent);
    // Set request body to HTTP servlet request
    request.setContent(requestContent.toByteArray());
    // Set content type to HTTP servlet request (important, includes Mime boundary string)
    request.setContentType(multipartRequestEntity.getContentType());
}
About these ads
This entry was posted in Java, Spring, Testing and tagged , , , . Bookmark the permalink.

3 Responses to Mocking a multipart/form-data HTTP request in a unit test

  1. innomin says:

    Huge help! Couldn’t find this anywhere else.

  2. javierco says:

    WOW, you just saved my life!!! THANKS :D

  3. Steph says:

    So, how to do this with servlet 2.5 API? It does not know javax.servlet.http.Part yet. I have been looking for a way to mock this all over :( – but the 2.5 interface does not offer getPart() or getParts() – how can I get the mocked data into a request-dummy?

    Preferrably without any frameworks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s