测试 POST 请求与 Spring 的 multipartfile

Test POST request with multipartfile with Spring

我有一个发送 post 请求的控制器,它运行良好并与客户端正确通信。但是,我无法在 JUnit 中对其进行测试。 控制器接收一个多部分文件,以及 2 个布尔参数(必需),并且仅接受“application/xls”作为内容类型。 为了进行测试,我正在模拟 multipartfile 和参数。但是,当我这样做时,出现以下错误:handler.RestExceptionHandler: Exception caught. Wrong file type;\n Import .xls or .xlsx file(来自我的异常处理程序)。

    @PostMapping(value = "/file",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.TEXT_HTML_VALUE)
    public ResponseEntity<InputStreamResource> parseMultipartFile(
            @RequestParam MultipartFile multipartFile,
            @RequestParam boolean hasOnlyOneSheet,
            @RequestParam boolean hasBorders) throws IOException {

        String fileContentType = multipartFile.getContentType();
        if (mimeType.contains(fileContentType)) {

            InputStream parsedFile = multipartFileToHtmlService.multipartFileToHtml(multipartFile, hasOnlyOneSheet, hasBorders);
            InputStreamResource inputStreamResource = new InputStreamResource(parsedFile);

            return ResponseEntity.ok(inputStreamResource);
        } else {
            throw new UnsupportedImportMediaTypeException("Wrong file type;\n Import .xls or .xlsx file");
        }
    }

这是我的测试:

@WebMvcTest
@RunWith(SpringRunner.class)
class HtmlExporterControllerTest {

    @MockBean
    MultipartFileToHtmlService multipartFileToHtmlService;

    @MockBean
    HtmlToHtmlServiceFactory htmlToHtmlServiceFactory;

    @Autowired
    MockMvc mockMvc;

    @Test
   public void parseMultipartFile_Should_Return_Ok() throws Exception {
        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "multipartFile",
                "test.xls",
                "application/x-xls",
                "Hello World!".getBytes());

        mockMvc.perform(MockMvcRequestBuilders.multipart("/file")
                .file("multipartFile", mockMultipartFile.getBytes())
                .param("hasOnlyOneSheet", "true")
                .param("hasBorders", "true"))
                .andExpect(status().isOk());
    }

为了避免这个问题,我尝试将布尔值作为新 multipart/form-data 传递,如下所示:

    @Test
   public void parseMultipartFile_Should_Return_Ok() throws Exception {
        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "multipartFile",
                "test.xls",
                "application/x-xls",
                "Hello World!".getBytes());

        MockMultipartFile mockMultipartFile1 = new MockMultipartFile(
                "hasBorders",
                "",
                "",
                "true".getBytes());

        MockMultipartFile mockMultipartFile2 = new MockMultipartFile(
                "hasOnlyOneSheet",
                "",
                "",
                "true".getBytes());

        mockMvc.perform(MockMvcRequestBuilders.multipart("/file")
                .file("multipartFile", mockMultipartFile.getBytes())
                .file("hasOnlyOneSheet", mockMultipartFile1.getBytes())
                .file("hasBorders", mockMultipartFile2.getBytes()))
                .andExpect(status().isOk());
    }

但是,我得到以下错误Failed to convert value of type 'org.springframework.mock.web.MockMultipartFile' to required type 'boolean';

再一次,请求有效,我也可以在 Postman 上执行,这里是 curl 请求:

curl --location --request POST 'http://localhost:8080/file' \
--form 'multipartFile=@/MyPath/test.xlsx' \
--form 'hasBorders=true' \
--form 'hasOnlyOneSheet=true'

为了帮助其他人,我通过添加一个真正的 excel sheet:

来解决它
@WebMvcTest
@RunWith(SpringRunner.class)
class HtmlExporterControllerTest {

@MockBean
MultipartFileToHtmlService multipartFileToHtmlService;

@MockBean
HtmlToHtmlServiceFactory htmlToHtmlServiceFactory;

@Autowired
MockMvc mockMvc;

@Test
public void parseMultipartFile_Should_Return_Ok() throws Exception {
    MockMultipartFile mockMultipartFile = new MockMultipartFile(
            "multipartFile",
            "test.xls",
            "application/x-xls",
            new ClassPathResource("test.xls").getInputStream());

    mockMvc.perform(MockMvcRequestBuilders.multipart("/file")
            .file(mockMultipartFile)
            .param("hasOnlyOneSheet", "true")
            .param("hasBorders", "true"))
            .andExpect(status().isOk());
}