如何使用junit使用MultiPart参数测试REST API?

时间:2017-02-09 12:23:13

标签: java rest junit multipart

我需要一些关于测试POST REST功能的帮助,

我有这个REST函数头:

@RequestMapping(value = "/import", method = RequestMethod.POST)
    public @ResponseBody
    HistoricalDataImportResponse importHistoricalDataFile(String fileFormat, @RequestParam("file") MultipartFile stream)  {

我尝试使用JUnit对此测试进行测试:

@Test
public void testHistoricalDataImport() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    FileItem fileItem = new DiskFileItem(null, null, false, null, 0, null);
    MultipartFile eventRequest = new CommonsMultipartFile(null);
    String body = mapper.writeValueAsString(eventRequest);

    //when
    MvcResult result = this.mockMvc.perform(post("/historicaldata/import").contentType(MediaType.MULTIPART_FORM_DATA).content(body))
            .andExpect(status().isOk())
            .andReturn();
}

运行测试时fileItem为空,如何将某个文件传递给我的REST函数?

2 个答案:

答案 0 :(得分:1)

最终测试如下:

 @Test
    public void testHistoricalDataImport() throws Exception {
        MockMultipartFile firstFile = new MockMultipartFile("file", "filename.csv", "text/plain", "some CSV data".getBytes());
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.fileUpload("/historicaldata/import")
                .file(firstFile);

        MvcResult result = mockMvc.perform(requestBuilder)
                .andExpect(status().isOk())
                .andReturn();
    }

答案 1 :(得分:0)

通过查看代码,您似乎想要从文件系统中读取文件,然后使用objectMapper将其转换为JSON。这是编写单元测试的不正确方法,您不能从单元测试中访问文件系统,您的测试应该独立运行。使用以下代码

  @Test
  public void testHistoricalDataImport() throws Exception {
    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.fileUpload("/historicaldata/import")
            .file("filename","some data as file text".getBytes());

    MvcResult result = mockMvc.perform(requestBuilder).andExpect(status().isOk()).andReturn();
  }