java - 测试中未抛出 MaxUploadSizeExceededException

标签 java spring spring-mvc junit multipartform-data

我有一个简单的 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/

相关文章:

java - 在java中使用正则表达式与不可打印的字符

java - 一个集合中的spring data jpa查询值

Spring异常处理程序记录所有异常但返回原始响应

spring - 什么 CMS 用于 Spring MVC Web 应用程序和设备响应式 Web 设计?

java - Spring MVC、 hibernate : Lazy initialization exception

java - 使用 Hibernate 与托管提供商创建 MySQL 数据库模式、优缺点、实践。

java - 为 JMS 发布者/消费者设置 clientID 的目的是什么?

java - jackson 将不同的字符串反序列化为相同的枚举常量

java - 原型(prototype) spring bean 只给我一个类的实例

java - HIbernate 更新与 null ononetomany 关系