英文:
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 = "/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
java.lang.AssertionError: Status expected:<202> but was:<415>
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("/attachment")
.file(mockMultipartFile)
.content(objectMapper.writeValueAsString(documentRequest))
.contentType(MediaType.APPLICATION_JSON);// <<<
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论