JamesD
JamesD

Reputation: 719

Testing for file upload in Spring MVC

Project setup:

    <java.version>1.8</java.version>
    <spring.version>4.3.9.RELEASE</spring.version>
    <spring.boot.version>1.4.3.RELEASE</spring.boot.version>

We have a REST controller that has a method to upload file like this:

@PostMapping("/spreadsheet/upload")
public ResponseEntity<?> uploadSpreadsheet(@RequestBody MultipartFile file) {
    if (null == file || file.isEmpty()) {
        return new ResponseEntity<>("please select a file!", HttpStatus.NO_CONTENT);
    } else if (blueCostService.isDuplicateSpreadsheetUploaded(file.getOriginalFilename())) {
        return new ResponseEntity<>("Duplicate Spreadsheet. Please select a different file to upload",
                HttpStatus.CONFLICT);
    } else {
        try {
            saveUploadedFiles(Arrays.asList(file));

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity("Successfully uploaded - " + file.getOriginalFilename(), new HttpHeaders(),
                HttpStatus.OK);
    }

}

UPDATE: I've tried this approach from an old example I found, but it doesn't compile cleanly, the MockMvcRequestBuilders.multipart method is not defined....

@Test    
    public void testUploadSpreadsheet_Empty() throws Exception {

        String fileName = "EmptySpreadsheet.xls";
        String content  = "";

        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "emptyFile",
                fileName,
                "text/plain",
                content.getBytes());

        System.out.println("emptyFile content is '" + mockMultipartFile.toString() + "'.");

        mockMvc.perform(MockMvcRequestBuilders.multipart("/bluecost/spreadsheet/upload")
                .file("file", mockMultipartFile.getBytes())
                .characterEncoding("UTF-8"))
        .andExpect(status().isOk());

    }

Upvotes: 0

Views: 583

Answers (1)

Arho Huttunen
Arho Huttunen

Reputation: 1131

I believe MockMvcRequestBuilders.multipart() is only available since Spring 5. What you want is MockMvcRequestBuilders.fileUpload() that is available in Spring 4.

Upvotes: 1

Related Questions