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

问题描述 投票:0回答:1

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

我该如何解决?

java spring-mvc junit spring-restcontroller mockmvc
1个回答
0
投票
尝试:

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

© www.soinside.com 2019 - 2024. All rights reserved.