Spring MVC MockMvc集成或单元测试POST API,该API采用@Valid Object、BindingResult、MultipartFile等参数

btxsgosb  于 2022-11-14  发布在  Spring
关注(0)|答案(1)|浏览(146)

我如何测试一个采用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);
    }
z6psavjg

z6psavjg1#

问题是我没有传递参数,就像我使用post man测试我的api一样。所以基本上就是这样。

@Test
    void newProduct() {
        // Given
        MockMultipartFile multipartFile = new MockMultipartFile("file",
                "fresh-pepper.jpg",
                "image/png, image/jpg, image/jpeg",
                "random image".getBytes());

        //Then
        try {
            this.mockMvc.perform(
                    multipart("/secured/api/v2/addNew")
                            .file(multipartFile)
                            .param("name", "Test")
                            .param("category", "Test")
                            .param("description", "Lorem 23")
                    )
                    .andDo(print())
                    .andExpect(status().isOk());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

相关问题