G_Yahia
G_Yahia

Reputation: 91

How to unit test a multipart POST request with Spring MVC Test?

I am trying to create unit test for REST APi but having big trouble with the uploading excel method.

Here is the method on the controller side

@RestController()
@RequestMapping(path = "/upload")
@CrossOrigin(origins = "http://localhost:4200")

public class FileController {
@Autowired
FileService fileService;

@PostMapping(value = "/{managerId}/project/{projectId}")
public List<Task> importExcelFile(@RequestParam("file") MultipartFile files, @PathVariable int managerId,
        @PathVariable int projectId) throws IOException, ParseException {

    return fileService.getTasksFromExcel(files, managerId, projectId);
}

Whatever I try I get a lot of errors and evidently I don't really understand what I am supposed to do.

The main error I get is

current request is not a multipart request

Upvotes: 1

Views: 6631

Answers (2)

Joe
Joe

Reputation: 150

Generally Multipart uploads can be tested via MockMultipartFile: https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/file-upload-test.html

Upvotes: 0

Mansur
Mansur

Reputation: 1829

You can do the following.

I just simplified your example a tiny bit.

So, here's the controller that returns the file size of the file it receives.

@RestController
@RequestMapping(path = "/upload")
public class FileController {
    @PostMapping(value = "/file")
    public ResponseEntity<Object> importExcelFile(@RequestParam("file") MultipartFile files) {
        return ResponseEntity.ok(files.getSize());
    }
}

and this one is the test of it. There is a class called MockMvc that Spring provides to easily unit test your controllers and controller advices. There is a method called multipart that you can use to simulate file upload cases.

class FileControllerTest {

    private final MockMvc mockMvc = MockMvcBuilders
            .standaloneSetup(new FileController())
            .build();

    @Test
    @SneakyThrows
    void importExcelFile() {
        final byte[] bytes = Files.readAllBytes(Paths.get("TEST_FILE_URL_HERE"));
        mockMvc.perform(multipart("/upload/file")
                .file("file", bytes))
                .andExpect(status().isOk())
                .andExpect(content().string("2037")); // size of the test input file
    }
}

Upvotes: 2

Related Questions