我如何测试一个采用Multipartfile等参数的post api方法。根据Spring文档,我知道我必须使用multipart而不是post for MockMvc,但是我的响应状态是400而不是200。(请随意使用您自己的示例来给予我如何测试这个)。
测试类和方法
@Autowired
private MockMvc mockMvc;
@MockBean
private ProductService productService;
@Test
void newProduct() {
// Given
Product product = new Product("Test", "Diary", "Lorem 24", "fresh-pepper.jpg");
product.setId(1L);
product.setPath("dummy photo path");
MockMultipartFile multipartFile = new MockMultipartFile("file",
"fresh-pepper.jpg",
"image/png, image/jpg, image/jpeg",
"random image".getBytes());
//When
when(productService.saveProduct(product, multipartFile)).thenReturn(product);
//Then
try {
this.mockMvc.perform(multipart("/dummy/api/v1/addNew")
.file(multipartFile))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception e) {
e.printStackTrace();
}
}
Rest API方法和NOTE @RequestMapping("/dummy/api/v1")
@PostMapping(path = "/addNew", consumes = {MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<Product> newProduct(@Valid Product product,
BindingResult bindingResult,
@RequestParam("file") MultipartFile file) {
if (bindingResult.hasFieldErrors()){
bindingResult.getFieldErrors().forEach(fieldError -> LOGGER.error("Error " + fieldError.getField()));
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(productService.saveProduct(product, file), HttpStatus.OK);
}
1条答案
按热度按时间z6psavjg1#
问题是我没有传递参数,就像我使用post man测试我的api一样。所以基本上就是这样。