简体   繁体   English

如何将文件和正文添加到 MockMvc?

[英]How to add a file and body to MockMvc?

Using Spring boot 2 and Spring mvc.使用 Spring 引导 2 和 Spring mvc。 I am trying to test my rest controller using mockMvc我正在尝试使用 mockMvc 测试我的 rest 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我收到415状态错误

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

How could I fix it?我该如何解决?

You're getting status 415: unsupported media type.您收到状态 415:不支持的媒体类型。

You needed to changed add contentType() of the request which the controller accepts.您需要更改 controller 接受的请求的 add contentType() If your controller accepts application/json :如果您的 controller 接受application/json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM