spring - 使用 MockMultipartFile 测试最大上传文件大小

标签 spring spring-mvc spring-boot spring-test spring-test-mvc

我使用 Spring Boot 创建一个文件上传服务,并使用 Spring Mock Mvc 和 MockMultipartFile 对其进行测试。我想测试当超过最大文件大小时是否抛出错误。以下测试失败,因为它收到 200。

RandomAccessFile f = new RandomAccessFile("t", "rw");
f.setLength(1024 * 1024 * 10);
InputStream is = Channels.newInputStream(f.getChannel());

MockMultipartFile firstFile = new MockMultipartFile("data", "file1.txt", "text/plain", is);

mvc.perform(fileUpload("/files")
    .file(firstFile))
    .andExpect(status().isInternalServerError());

是否可以测试上传文件大小?

最佳答案

根据documentation :

If the present length of the file as returned by the length method is smaller than the newLength argument then the file will be extended. In this case, the contents of the extended portion of the file are not defined.

试试这个:

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

关于spring - 使用 MockMultipartFile 测试最大上传文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33667276/

相关文章:

java - 使用spring框架发送邮件时出现错误

Spring Security 用户名密码AuthenticationFilter : How to access Request after a failed login

java - Spring MVC : RequestMapping both class and method

spring-mvc - 使用Spring Boot启动服务器时出现多个错误

java - 在 Spring Controller 中返回原始类型/包装器的最佳方法是什么?

java - spring框架动态日志记录

java - 在同一事务中更新两个对象

java - 邮件发送异常 : Failed messages: com. sun.mail.smtp.SMTPSendFailedException

java - Spring Web MVC : Regex in controller mapping

java - Spring Batch 限制跨多个服务器的单个作业实例