Issue
I create a file upload service with Spring Boot and test it with Spring Mock Mvc and MockMultipartFile. I want to test if an error is thrown when the maximum file size is exceeded. The following test fails because it receive a 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());
Is there any possibility to test the upload file size?
Solution
According to the 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.
Try this instead:
byte[] bytes = new byte[1024 * 1024 * 10];
MockMultipartFile firstFile = new MockMultipartFile("data", "file1.txt", "text/plain", bytes);
Answered By - jny