【发布时间】: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
- 有没有一种方法可以模拟和指定文件大小?
- 或者实际上传递一个真正的大文件进行测试(最好不要)?
- 或者更好的方法,测试我可以接受最大 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());
}
【问题讨论】:
标签: java spring spring-boot unit-testing