首页 > 解决方案 > 如何将文件和正文添加到 MockMvc?

问题描述

使用 Spring Boot 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

我该如何解决?

标签: javaspring-mvcjunitspring-restcontrollermockmvc

解决方案


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

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

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

推荐阅读