首页 > 解决方案 > 如何使用 Spring MVC Test 对多部分 POST 请求进行单元测试?

问题描述

我正在尝试为 REST APi 创建单元测试,但在上传 excel 方法时遇到了很大问题。

这是控制器端的方法

@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);
}

无论我尝试什么,我都会遇到很多错误,显然我并不真正了解我应该做什么。

我得到的主要错误是

current request is not a multipart request

标签: spring-bootspring-mvcjunit

解决方案


您可以执行以下操作。

我只是稍微简化了你的例子。

所以,这是一个控制器,它返回它接收到的文件的文件大小。

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

这就是对它的考验。Spring 提供了一个名为 MockMvc 的类,可以轻松地对控制器和控制器建议进行单元测试。有一种称为multipart的方法,您可以使用它来模拟文件上传案例。

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
    }
}

推荐阅读