使用Spring MVC Test对多部分POST请求进行单元测试

 Sadness_小妖_619 发布于 2023-01-26 23:16

我有以下请求处理程序来保存汽车.我已经证实,当我使用例如cURL时,这是有效的.现在我想用Spring MVC Test对方法进行单元测试.我曾尝试使用fileUploader,但我无法让它运行起来.我也没有设法添加JSON部分.

我如何使用Spring MVC Test对此方法进行单元测试?我无法找到任何这方面的例子.

@RequestMapping(value = "autos", method = RequestMethod.POST)
public ResponseEntity saveAuto(
    @RequestPart(value = "data") autoResource,
    @RequestParam(value = "files[]", required = false) List files) {
    // ...
}

我想为我的自动+一个或多个文件上传一个JSON表示.

我会在正确的答案中加上100分!

3 个回答
  • 由于MockMvcRequestBuilders#fileUpload不推荐使用,您将需要使用MockMvcRequestBuilders#multipart(String, Object...)哪个返回a MockMultipartHttpServletRequestBuilder.然后链接一堆file(MockMultipartFile)电话.

    这是一个有效的例子.给出一个@Controller

    @Controller
    public class NewController {
    
        @RequestMapping(value = "/upload", method = RequestMethod.POST)
        @ResponseBody
        public String saveAuto(
                @RequestPart(value = "json") JsonPojo pojo,
                @RequestParam(value = "some-random") String random,
                @RequestParam(value = "data", required = false) List<MultipartFile> files) {
            System.out.println(random);
            System.out.println(pojo.getJson());
            for (MultipartFile file : files) {
                System.out.println(file.getOriginalFilename());
            }
            return "success";
        }
    
        static class JsonPojo {
            private String json;
    
            public String getJson() {
                return json;
            }
    
            public void setJson(String json) {
                this.json = json;
            }
    
        }
    }
    

    和单元测试

    @WebAppConfiguration
    @ContextConfiguration(classes = WebConfig.class)
    @RunWith(SpringJUnit4ClassRunner.class)
    public class Example {
    
        @Autowired
        private WebApplicationContext webApplicationContext;
    
        @Test
        public void test() throws Exception {
    
            MockMultipartFile firstFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes());
            MockMultipartFile secondFile = new MockMultipartFile("data", "other-file-name.data", "text/plain", "some other type".getBytes());
            MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", "{\"json\": \"someValue\"}".getBytes());
    
            MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
            mockMvc.perform(MockMvcRequestBuilders.multipart("/upload")
                            .file(firstFile)
                            .file(secondFile)
                            .file(jsonFile)
                            .param("some-random", "4"))
                        .andExpect(status().is(200))
                        .andExpect(content().string("success"));
        }
    }
    

    @Configuration班级

    @Configuration
    @ComponentScan({ "test.controllers" })
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurationSupport {
        @Bean
        public MultipartResolver multipartResolver() {
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
            return multipartResolver;
        }
    }
    

    测试应该通过并给你输出

    4 // from param
    someValue // from json file
    filename.txt // from first file
    other-file-name.data // from second file
    

    需要注意的是,您正在发送JSON,就像任何其他多部分文件一样,除了具有不同的内容类型.

    2023-01-26 23:39 回答
  • MockMvcRequestBuilders.fileUpload不推荐使用该方法MockMvcRequestBuilders.multipart.

    这是一个例子:

    import static org.hamcrest.CoreMatchers.containsString;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.mock.web.MockMultipartFile;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.ResultActions;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.multipart.MultipartFile;
    
    
    /**
     * Unit test New Controller.
     *
     */
    @RunWith(SpringRunner.class)
    @WebMvcTest(NewController.class)
    public class NewControllerTest {
    
        private MockMvc mockMvc;
    
        @Autowired
        WebApplicationContext wContext;
    
        @MockBean
        private NewController newController;
    
        @Before
        public void setup() {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(wContext)
                       .alwaysDo(MockMvcResultHandlers.print())
                       .build();
        }
    
       @Test
        public void test() throws Exception {
           // Mock Request
            MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());
    
            // Mock Response
            NewControllerResponseDto response = new NewControllerDto();
            Mockito.when(newController.postV1(Mockito.any(Integer.class), Mockito.any(MultipartFile.class))).thenReturn(response);
    
            mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
                    .file("file", jsonFile.getBytes())
                    .characterEncoding("UTF-8"))
            .andExpect(status().isOk());
    
        }
    
    }
    

    2023-01-26 23:43 回答
  • 看看这个从spring MVC展示中获取的例子,这是源代码的链接:

    @RunWith(SpringJUnit4ClassRunner.class)
    public class FileUploadControllerTests extends AbstractContextControllerTests {
    
        @Test
        public void readString() throws Exception {
    
            MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
    
            webAppContextSetup(this.wac).build()
                .perform(fileUpload("/fileupload").file(file))
                .andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
        }
    
    }
    

    2023-01-26 23:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有