【问题标题】:Spring Boot: file upload testingSpring Boot:文件上传测试
【发布时间】:2020-01-14 21:10:28
【问题描述】:

我正在尝试在 Spring REST 应用程序中创建单元测试。该测试与 MultipartFile 上传的端点有关。

这是我的方法在@RestController 中接受的参数

@PostMapping("/upload")
    public ResponseEntity uploadFile(@HasFileName @RequestParam("file") MultipartFile file,
                                     @NotEmpty @RequestParam("entity") String entity, @NotEmpty @RequestParam("language") String language,
                                     @NotEmpty @RequestParam("lastModified") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime lastModifiedDateTime,
                                     @NotEmpty @RequestParam("createdDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime createdDateTime)
            throws IOException {

我找不到从单元测试中的多部分获取此信息的方法。我找不到有关为 Spring REST 进行弹簧单元测试的文档,因此我们将不胜感激。


@Test
    public void testUploadFile() throws Exception{
        ResultMatcher ok = MockMvcResultMatchers.status().isOk();

        String filename = "test.txt";
        File file = new File("/test" + filename);

        file.delete();

        MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "test.txt", "multipart/form-data", "test data".getBytes());

        upload.uploadFile(mockMultipartFile, mockMultipartFile.getName()) //missing more data

        //more logic on how to assert that the file is not empty 


    }

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

原则上测试应该验证uploadFile方法()的结果:

ResultActions result = 
this.mockMvc.perform(multipart("/svc").file(file)
        .header(HttpHeaders.AUTHORIZATION,
            "Bearer token"))
        .andExpect(content().string("response"))
        .andExpect(status().isOk());

该文件是一个输入参数,所以我不明白您为什么要验证它不为空:我相信验证与其他模拟的交互可能很有用(例如检查文件是否在 FileService.save( ) 方法)

【讨论】:

  • 还有一点需要注意:如果你模拟一个使用 File 的服务类,你可以验证参数不为空,但这只有在 RestController 中操作/准备参数时才有意义。请参阅 Mockito ArgumentCaptor
猜你喜欢
  • 1970-01-01
  • 2018-03-20
  • 2017-12-30
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多