如何测试是否可以上传大型多部分文件

kar*_*vai 5 java spring unit-testing spring-boot

如果我尝试推送一个大文件(任何超过 1MB 大小的文件),我的代码最初会被破坏。它现在工作正常,并且能够通过在属性文件中添加以下内容来适应我想要的文件大小。

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
Run Code Online (Sandbox Code Playgroud)

但是我如何对此编写适当的单元/集成测试以确保它允许文件大小高达 10MB?

下面有一个很好的测试示例(已接受的答案),但它使用模拟文件设置进行测试。 使用 Spring MVC Test 对多部分 POST 请求进行单元测试

  1. 有没有办法可以模拟并指定文件大小?
  2. 或者实际上传递一个真正的大文件进行测试(最好不是)?
  3. 或者更好的方法来做到这一点,测试我可以接受高达 10MB 的大文件吗?

这是要测试的方法

@PostMapping(path = "/example", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SomeResponse> upload(@PathVariable(@RequestPart("file") MultipartFile file) {

    //we won't even get inside thi method and would fail if the file size is over 1MB previously. 

    // It works currently when I add files with size above 1MB 
    // cos I added the above 2 lines (spring.servlet.... in the properties file)

    // some logic which works fine.

    SomeResponse obj = // 
    return new ResponseEntity<>(obj, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

这是当前的测试(还有其他测试来测试负面场景)

@Test
public void testValidUpload() throws Exception {
    String fileContents = "12345";
    String expectedFileContents = "12345\nSomeData";

    mockServer.expect(requestTo("http://localhost:8080/example"))
        .andExpect(method(HttpMethod.POST))
        .andExpect(expectFile("file", "test.csv", expectedFileContents))
        .andRespond(withStatus(HttpStatus.OK)
                .contentType(MediaType.TEXT_PLAIN)
                .body("done")
        );

    String response = this.mvc.perform(multipart("/example")
        .file(new MockMultipartFile("file", "filename.csv", MediaType.TEXT_PLAIN_VALUE, fileContents.getBytes())))
        .andExpect(status().isOk())
        .andExpect(content().contentType(APPLICATION_JSON))
        .andExpect(jsonPath("responseStatusCode", Matchers.equalTo("200")))
        .andExpect(jsonPath("httpStatus", Matchers.equalTo("OK")))
        .andReturn().getResponse().getContentAsString();

    Response response = objectMapper.readValue(response, Response.class);
    assertEquals(HttpStatus.OK, response.getHttpStatus());
    assertEquals(5, response.id());
}
Run Code Online (Sandbox Code Playgroud)

小智 0

你可以尝试这样的事情:

byte[] bytes = new byte[1024 * 1024 * 10];
MockMultipartFile firstFile = new MockMultipartFile("data", "file1.txt", "text/plain", bytes);
Run Code Online (Sandbox Code Playgroud)

请参阅文档

您也可以参考这篇文章