如何向 MockMvc 中添加文件和请求体?

huangapple go评论83阅读模式
英文:

How to add a file and body to MockMvc?

问题

使用Spring Boot 2和Spring MVC。我试图使用mockMvc测试我的REST控制器。

@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

我该如何修复这个问题?

英文:

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

    @PostMapping(
        value = &quot;/attachment&quot;)
public ResponseEntity attachment(MultipartHttpServletRequest file, @RequestBody DocumentRequest body) {
    
    Document document;
    
    try {
        
        document = documentService.process(file.getFile(&quot;file&quot;), body);
        
    } catch (IOException | NullPointerException e) {
        
        return ResponseEntity.badRequest().body(e.getMessage());
        
    }
    
    return ResponseEntity.accepted().body(DocumentUploadSuccess.of(
            document.getId(),
            &quot;Document Uploaded&quot;,
            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(&quot;Upload Document&quot;)
public void testController() throws Exception {
    
    byte[] attachedfile = IOUtils.resourceToByteArray(&quot;/request/document-text.txt&quot;);
    
    MockMultipartFile mockMultipartFile = new MockMultipartFile(&quot;file&quot;, &quot;&quot;,
            &quot;text/plain&quot;, attachedfile);
    
    
    DocumentRequest documentRequest = new DocumentRequest();
    documentRequest.setApplicationId(&quot;_APP_ID&quot;);
    
    MockHttpServletRequestBuilder builder =
            MockMvcRequestBuilders
                    .fileUpload(&quot;/attachment&quot;)
                    .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(&quot;id&quot;).asText();
    
    Assert.assertTrue(documentRepository.findById(id).isPresent());
    
}

I got 415 status error

java.lang.AssertionError: Status expected:&lt;202&gt; but was:&lt;415&gt;
Expected :202
Actual   :415

How could I fix it?

答案1

得分: 0

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

您需要修改请求的contentType(),使其与控制器所接受的内容类型一致。
如果您的控制器接受 application/json

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

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(&quot;/attachment&quot;)
                        .file(mockMultipartFile)
                        .content(objectMapper.writeValueAsString(documentRequest))
                        .contentType(MediaType.APPLICATION_JSON);// &lt;&lt;&lt;

huangapple
  • 本文由 发表于 2020年5月30日 05:42:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/62094999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定