Search code examples
javaspring-mvcjunitspring-restcontrollermockmvc

How to add a file and body to MockMvc?


Using Spring boot 2 and Spring mvc. I am trying to test my rest controller using mockMvc

    @PostMapping(
        value = "/attachment")
public ResponseEntity attachment(MultipartHttpServletRequest file, @RequestBody DocumentRequest body) {

    Document document;

    try {

        document = documentService.process(file.getFile("file"), body);

    } catch (IOException | NullPointerException e) {

        return ResponseEntity.badRequest().body(e.getMessage());

    }

    return ResponseEntity.accepted().body(DocumentUploadSuccess.of(
            document.getId(),
            "Document Uploaded",
            LocalDateTime.now()
    ));

}

I could attach the file successfully on my test but know I added a body and I can't receive both attached

    @Test
@DisplayName("Upload Document")
public void testController() throws Exception {

    byte[] attachedfile = IOUtils.resourceToByteArray("/request/document-text.txt");

    MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "",
            "text/plain", attachedfile);


    DocumentRequest documentRequest = new DocumentRequest();
    documentRequest.setApplicationId("_APP_ID");

    MockHttpServletRequestBuilder builder =
            MockMvcRequestBuilders
                    .fileUpload("/attachment")
                    .file(mockMultipartFile)
                    .content(objectMapper.writeValueAsString(documentRequest));

    MvcResult result = mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isAccepted())
            .andDo(MockMvcResultHandlers.print()).andReturn();

    JsonNode response = objectMapper.readTree(result.getResponse().getContentAsString());

    String id = response.get("id").asText();

    Assert.assertTrue(documentRepository.findById(id).isPresent());

}

I got 415 status error

java.lang.AssertionError: Status expected:<202> but was:<415>
Expected :202
Actual   :415

How could I fix it?


Solution

  • You're getting status 415: unsupported media type.

    You needed to changed add contentType() of the request which the controller accepts. If your controller accepts application/json:

            MockHttpServletRequestBuilder builder =
                    MockMvcRequestBuilders
                            .multipart("/attachment")
                            .file(mockMultipartFile)
                            .content(objectMapper.writeValueAsString(documentRequest))
                            .contentType(MediaType.APPLICATION_JSON);// <<<