gpt4 book ai didi

java - 测试中未抛出 MaxUploadSizeExceededException

转载 作者:行者123 更新时间:2023-12-01 11:20:00 27 4
gpt4 key购买 nike

我有一个简单的 spring 应用程序,带有一个需要多部分文件的 Controller 。出于测试目的,我设置了 MaxUploadSize大小仅为 50 字节。当我在 tomcat 中部署 war 时,我得到了预期的 MaxUploadSizeExceededException对于较大的文件,但如果我在单元测试中使用相同的文件,则测试不起作用。

配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = {...})
public class MyApplication extends WebMvcConfigurerAdapter {

@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver =
new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(50);
return commonsMultipartResolver;
}
}

@RestController
@RequestMapping("/metadata")
public class MyController {

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public String metadata(@RequestParam MultipartFile file) {
//some processing...
}
}

测试
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyApplication.class)
public class MyControllerTest {
...
@Test
public void testDocx() throws Exception {
byte[] docx = FileUtils.readFileToByteArray(new File(
"src/test/resources/testdocs/test.docx"));
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.docx", "", docx);
this.mvc.perform(fileUpload("/metadata").file(multipartFile))
.andDo(print()).andExpect(status().is5xxServerError());
//doesn't work, returns 200
}
}

Spring 版本:4.1.6

最佳答案

我遇到了同样的问题,幸运的是我能够解决它。

我假设 this.mvcMockMvc 的一个实例.据此 spring文档:

Another useful approach is to not start the server at all but to test only the layer below that, where Spring handles the incoming HTTP request and hands it off to your controller. That way, almost of the full stack is used, and your code will be called in exactly the same way as if it were processing a real HTTP request but without the cost of starting the server. To do that, use Spring’s MockMvc and ask for that to be injected for you by using the @AutoConfigureMockMvc annotation on the test case.



由于没有启动服务器,这个异常是Tomcat抛出的,所以永远不会抛出。我只需要删除它并使用 TestRestTemplate用于调用端点并像魅力一样工作。有一个很好的例子 here .

关于java - 测试中未抛出 MaxUploadSizeExceededException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46097516/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com