如何使用MockMvc为DefaultMultipartHttpServletRequest控制器方法编写单元测试?

时间:2017-03-02 08:48:11

标签: java spring unit-testing

像这样的代码:

@RequestMapping(value = "/upload/{resource}",method=RequestMethod.POST)
@ResponseBody
public Object uploadfileUpload(@PathVariable("resource") String resource,DefaultMultipartHttpServletRequest request,HttpServletResponse resp,MultipartFile file) throws IOException {
    ......
}
代码中的

this.mockMvc.perform(mockMultipartHttpServletRequestBuilder)

只能发布MultipartHttpServletRequest,因为mockMultipartHttpServletRequestBuilder implements MultipartHttpServletRequestMultipartHttpServletRequest是一个界面。

如何创建一个DefaultMultipartHttpServletRequest类对象然后在mockMvc发布请求以完成我的单元测试?

1 个答案:

答案 0 :(得分:0)

@Test
public void testUploadARA3() throws Exception {
    FileInputStream file = new FileInputStream(
            "C:/test_42873.xlsm");
    MockMultipartFile multipartFile = new MockMultipartFile(
            "test_42873.xlsm", file);
    MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload(
            "/upload/{resource}", "ARA").accept(MediaType.ALL);
    mockMultipartHttpServletRequestBuilder.file(multipartFile);
    //mockMultipartHttpServletRequestBuilder.content("whatever");

    MockHttpServletRequest request;
    MvcResult response =   this.mockMvc.perform(mockMultipartHttpServletRequestBuilder).andDo(print())
            .andExpect(status().isOk()).andReturn();
    System.out.println(response.getResponse().getContentAsString());

}

我的测试代码没有输入uploadfileUpload methord。