【问题标题】:How to unit test a multipart POST request with Spring MVC Test?如何使用 Spring MVC Test 对多部分 POST 请求进行单元测试?
【发布时间】:2020-09-24 21:11:04
【问题描述】:

我正在尝试为 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-boot spring-mvc junit


    【解决方案1】:

    您可以执行以下操作。

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

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

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

    【讨论】:

    • 感谢您的帮助
    【解决方案2】:

    通常可以通过 MockMultipartFile 测试分段上传: https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/file-upload-test.html

    【讨论】:

      猜你喜欢
      • 2014-03-15
      • 2016-09-15
      • 1970-01-01
      • 2012-05-25
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多