如何向 MockMvc 添加文件和正文?

How to add a file and body to MockMvc?

使用 Spring 引导 2 和 Spring mvc。我正在尝试使用 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()
    ));

}

我可以在测试中成功附加文件,但我知道我添加了一个正文,但我无法同时接收两个附件

    @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());

}

我收到 415 状态错误

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

我该如何解决?

您收到状态 415:不支持的媒体类型。

您需要更改控制器接受的请求的添加 contentType()。 如果您的控制器接受 application/json:

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