Search code examples
javajunitmockingmultipartform-dataspark-java

How to mock multipart/form-data with Java and Spark?


I'm receiving a file using multipart/form-data like I'll show you right below (Using Spark, not SpringBoot):

 @Override
public Object handle(Request request, Response response) throws Exception {
    request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(""));

    Part filePart = request.raw().getPart("file");
    String regex = request.raw().getParameter("regex");
    String fileName = filePart.getSubmittedFileName();
    byte[] fileBytes = filePart.getInputStream().readAllBytes();

The thing is, I want to unit test this Controller, and in order to do so, I need a way to mock the request to have a multipart/form-data inside, or at least a way to use "when...theReturn" to mimic that part of code... Any ideas?

Thanks in advance!


Solution

  • So I managed to find the answer to this question and I thought maybe I could help other people by answering it:

    @Test
    public void whenValidRegex_returnOkAndTotalAmount() throws Exception {
        final Part file = mock(MultiPartInputStreamParser.MultiPart.class);
        final Request mock = mock(Request.class); //Spark request
        final Response mockResponse = mock(Response.class); //Spark response
        final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); //Javax servlet
    
        when(mock.raw()).thenReturn(httpServletRequest);
        when(file.getSubmittedFileName()).thenReturn("file.pdf");
        when(mock.raw().getParameter("regex")).thenReturn(String.valueOf("SOME REGEX"));
        when(mock.params("numPage")).thenReturn(String.valueOf("1"));
        when(file.getInputStream()).thenReturn(IOUtils.toInputStream("ARGENTINIAN PESOS", Charset.defaultCharset())); //Here you are mocking the input stream you might get from the part file.
        when(mock.raw().getPart("file")).thenReturn(file);
    

    Now that you have the multipart/form-data mocked, you can continue your test mocking the service calls and such things. Please ignore things that are from my specific code, like the "Page number" mocking, you don't need that. Hope this helps for someone else. Bye!