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

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

How to add a file and body to MockMvc?

问题

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

  1. @PostMapping(
  2. value = "/attachment")
  3. public ResponseEntity attachment(MultipartHttpServletRequest file, @RequestBody DocumentRequest body) {
  4. Document document;
  5. try {
  6. document = documentService.process(file.getFile("file"), body);
  7. } catch (IOException | NullPointerException e) {
  8. return ResponseEntity.badRequest().body(e.getMessage());
  9. }
  10. return ResponseEntity.accepted().body(DocumentUploadSuccess.of(
  11. document.getId(),
  12. "Document Uploaded",
  13. LocalDateTime.now()
  14. ));
  15. }

我可以成功地在测试中附加文件,但现在我添加了一个请求体,我不能同时接收附加的文件。

  1. @Test
  2. @DisplayName("Upload Document")
  3. public void testController() throws Exception {
  4. byte[] attachedfile = IOUtils.resourceToByteArray("/request/document-text.txt");
  5. MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "",
  6. "text/plain", attachedfile);
  7. DocumentRequest documentRequest = new DocumentRequest();
  8. documentRequest.setApplicationId("_APP_ID");
  9. MockHttpServletRequestBuilder builder =
  10. MockMvcRequestBuilders
  11. .fileUpload("/attachment")
  12. .file(mockMultipartFile)
  13. .content(objectMapper.writeValueAsString(documentRequest));
  14. MvcResult result = mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isAccepted())
  15. .andDo(MockMvcResultHandlers.print()).andReturn();
  16. JsonNode response = objectMapper.readTree(result.getResponse().getContentAsString());
  17. String id = response.get("id").asText();
  18. Assert.assertTrue(documentRepository.findById(id).isPresent());
  19. }

我得到了415状态错误。

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

我该如何修复这个问题?

英文:

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

  1. @PostMapping(
  2. value = &quot;/attachment&quot;)
  3. public ResponseEntity attachment(MultipartHttpServletRequest file, @RequestBody DocumentRequest body) {
  4. Document document;
  5. try {
  6. document = documentService.process(file.getFile(&quot;file&quot;), body);
  7. } catch (IOException | NullPointerException e) {
  8. return ResponseEntity.badRequest().body(e.getMessage());
  9. }
  10. return ResponseEntity.accepted().body(DocumentUploadSuccess.of(
  11. document.getId(),
  12. &quot;Document Uploaded&quot;,
  13. LocalDateTime.now()
  14. ));
  15. }

I could attach the file successfully on my test but know I added a body and I can't receive both attached

  1. @Test
  2. @DisplayName(&quot;Upload Document&quot;)
  3. public void testController() throws Exception {
  4. byte[] attachedfile = IOUtils.resourceToByteArray(&quot;/request/document-text.txt&quot;);
  5. MockMultipartFile mockMultipartFile = new MockMultipartFile(&quot;file&quot;, &quot;&quot;,
  6. &quot;text/plain&quot;, attachedfile);
  7. DocumentRequest documentRequest = new DocumentRequest();
  8. documentRequest.setApplicationId(&quot;_APP_ID&quot;);
  9. MockHttpServletRequestBuilder builder =
  10. MockMvcRequestBuilders
  11. .fileUpload(&quot;/attachment&quot;)
  12. .file(mockMultipartFile)
  13. .content(objectMapper.writeValueAsString(documentRequest));
  14. MvcResult result = mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isAccepted())
  15. .andDo(MockMvcResultHandlers.print()).andReturn();
  16. JsonNode response = objectMapper.readTree(result.getResponse().getContentAsString());
  17. String id = response.get(&quot;id&quot;).asText();
  18. Assert.assertTrue(documentRepository.findById(id).isPresent());
  19. }

I got 415 status error

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

How could I fix it?

答案1

得分: 0

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

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

  1. MockHttpServletRequestBuilder builder =
  2. MockMvcRequestBuilders
  3. .multipart("/attachment")
  4. .file(mockMultipartFile)
  5. .content(objectMapper.writeValueAsString(documentRequest))
  6. .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:

  1. MockHttpServletRequestBuilder builder =
  2. MockMvcRequestBuilders
  3. .multipart(&quot;/attachment&quot;)
  4. .file(mockMultipartFile)
  5. .content(objectMapper.writeValueAsString(documentRequest))
  6. .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:

确定