Integration test case and file upload

2019-09-09 11:43发布

I wrote some code for related to upload a file using spring, It works fine, Now I am writing integration test cases for that but I am facing some issue My controller method,

@RequestMapping(value = "/{attributeName}/upload", method = RequestMethod.POST)
@ResponseBody
public Result uploadCompany(HttpServletRequest request,
        @RequestParam MultipartFile file, @PathVariable String attributeName,
        @RequestParam long dateKey)
        throws IOException, PromotionException {
    some code
}

Test cases

@Test
public void shouldReturnTrueStatusWhenUploadCompany() throws Exception {
    MockMultipartFile file = new MockMultipartFile("company_upload", "company_upload.csv",
            MediaType.MULTIPART_FORM_DATA_VALUE, EMPLOYEE_NUMBER_FILE_CONTENT.getBytes(UTF_8));
    mockMvc.perform(
            MockMvcRequestBuilders.fileUpload(
                    PROMOTION + StringUtils.replace(ATTRIBUTE_NAME, "{attributeName}", "COMPANY") + "/upload")
                    .file(file).param("dateKey", "852017")  .contentType(MediaType.MULTIPART_FORM_DATA)
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());

}

But I am getting

2017-05-09 13:42:42,506 ERROR [Test worker] INTERNAL_SERVER_ERROR: 
org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present

Where am I wrong?

1条回答
仙女界的扛把子
2楼-- · 2019-09-09 11:45

change your line

 MockMultipartFile file = new MockMultipartFile("company_upload", "company_upload.csv",
                    MediaType.MULTIPART_FORM_DATA_VALUE, EMPLOYEE_NUMBER_FILE_CONTENT.getBytes(UTF_8));  

to

 MockMultipartFile file = new MockMultipartFile("file", "company_upload.csv",
                    MediaType.MULTIPART_FORM_DATA_VALUE, EMPLOYEE_NUMBER_FILE_CONTENT.getBytes(UTF_8));

or change your controller method declaration to something like this

 public Result uploadCompany(HttpServletRequest request,
                @RequestParam(value = "company_upload") MultipartFile file, @PathVariable String attributeName,
                @RequestParam long dateKey)
查看更多
登录 后发表回答