【问题标题】:How to test if I can upload a large multipart file如何测试我是否可以上传大型多部分文件
【发布时间】:2020-07-12 07:30:03
【问题描述】:

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

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

但是我怎样才能为此编写适当的单元/集成测试以确保它允许文件大小最大为 10MB?

以下有一个很好的测试示例(已接受的答案),但它使用模拟文件设置进行测试。 Using Spring MVC Test to unit test multipart POST request

  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);
}

这是当前测试(还有其他测试可以测试负面情况)

@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());
}

【问题讨论】:

  • HTTP 允许在实际将大负载发送到服务器之前检查服务器是否能够处理大文件。这里的前期请求包含一个Expect 标头与Content-TypeContent-Length 标头配对,因为RFC 7230 状态只是资源的预期大小的指示。这应该是相当直接的测试

标签: java spring spring-boot unit-testing


【解决方案1】:

你可以试试这样的:

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

documentation

你也可以参考这个article

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 2019-06-19
    • 2023-03-24
    • 2021-10-24
    • 1970-01-01
    • 2011-07-01
    • 2012-05-04
    • 2021-08-02
    相关资源
    最近更新 更多