我在junit5中使用spring-boot 2.0.3.RELEASE。我刚刚尝试用模拟Mvc测试多部分请求。
MockMultipartFile file = new MockMultipartFile("file", "contract.pdf", MediaType.APPLICATION_PDF_VALUE, "<<pdf data>>".getBytes(StandardCharsets.UTF_8));
MockMultipartFile metadata = new MockMultipartFile("metadata", "", MediaType.APPLICATION_JSON_VALUE, objectMapper.writeValueAsString(metadata).getBytes(StandardCharsets.UTF_8));
this.mockMvc.perform(multipart("/documents")
.file(file)
.file(metadata))
.andExpect(status().isNoContent());
但是它不适用于零件元数据(json)。
我总是会出现异常
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: originalFilename is required.
怎么了?
编辑:
我的实现是在spring集成dsl中。我认为该异常是在org.springframework.integration.http.multipart.UploadedMultipartFile
中调用的。我该如何使用嘲笑Mvc测试分段请求?
@Bean
public IntegrationFlow multipartForm() {
return IntegrationFlows.from(Http.inboundChannelAdapter("/documents")
.statusCodeExpression(HttpStatus.NO_CONTENT.toString())
.requestMapping(m -> m
.methods(HttpMethod.POST)
.consumes(MediaType.MULTIPART_FORM_DATA_VALUE)
))
.handle(new MultipartReceiver())
.get();
}
我的演示项目在github中 https://github.com/bulalak/demo-spring-integration-http
答案 0 :(得分:0)
您还没有共享您的控制器,所以我在这里写一个我的例子。
这是在春季启动中使用MultipartFile进行的测试:
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
UserService userService;
@Test
public void test() throws Exception {
UserCreateRequest request = new UserCreateRequest();
request.setName("test");
request.setBirthDate(new Date());
request.setGender("male");
MockMultipartFile file =
new MockMultipartFile(
"file",
"contract.pdf",
MediaType.APPLICATION_PDF_VALUE,
"<<pdf data>>".getBytes(StandardCharsets.UTF_8));
ObjectMapper objectMapper = new ObjectMapper();
MockMultipartFile metadata =
new MockMultipartFile(
"request",
"request",
MediaType.APPLICATION_JSON_VALUE,
objectMapper.writeValueAsString(request).getBytes(StandardCharsets.UTF_8));
mockMvc.perform(
multipart("/users/")
.file(file)
.file(metadata)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
用户控制器:
@RestController
@RequestMapping("/users")
public class UserController {
UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping({"/", ""})
public ResponseEntity<User> post(@RequestPart("request") UserCreateRequest request, @RequestPart("file") MultipartFile file) throws IOException {
String photoPath = UUID.randomUUID() + file.getOriginalFilename().replaceAll(" ", "").trim();
// other logic
request.setPhone(photoPath);
return ResponseEntity.ok(userService.create(request));
}
}
UserCreateRequest:
@Data // from lombok
public class UserCreateRequest {
private String name;
private String phone;
private String surname;
private String gender;
private Date birthDate;
private String bio;
private String photo;
}