【问题标题】:Testing MultipartFile with WebtestClient使用 WebtestClient 测试 MultipartFile
【发布时间】:2020-04-11 05:19:41
【问题描述】:

我正在为我的控制器类编写单元测试。我正在使用弹簧 webflux。因此,我正在使用WebTestClient 编写测试。这是我的控制器方法

@PutMapping("/updatedocument/{documentType}")
public ResponseEntity<String> updateDocument(@PathVariable String documentType,
                                             @RequestParam("file") MultipartFile file) {
     ...................
}

当我从 Postman 或任何其他客户端调用时,此代码正在运行。我在编写单元测试时遇到困难。我得到了

“所需的 MultipartFile 参数‘文件’不存在”

错误。这是我的测试方法。

@Test
void updateDocument() throws IOException {

    .............
    MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
    multipartBodyBuilder.part("file", new ClassPathResource("somefile"))
            .contentType(MediaType.MULTIPART_FORM_DATA)

    webTestClient.put()
            .uri("/customer/updatedocument/ID")
            .body(BodyInserters.fromMultipartData(multipartBodyBuilder.build()))
            .exchange()
            .expectStatus().isOk();
}

非常感谢任何建议。请注意。我使用的是WebTestClient 而不是MovkMvc

【问题讨论】:

    标签: java spring-boot unit-testing spring-webflux


    【解决方案1】:

    我能够解决这个问题。罪魁祸首是我的控制器方法而不是测试方法。

    必须在控制器方法中更改几件事。当使用 spring web Flux(reactive) 时,我们应该使用

    1.@RequestPart 而不是@RequestParam
    2.FilePart而不是MultipartFile

    所以控制器方法看起来像这样。

    @PutMapping("/updatedocument/{documentType}")
    public ResponseEntity<String> updateDocument(@PathVariable DocumentType documentType,
                                                 @RequestPart("file") FilePart filePart) {
       .....................
    }
    

    您可以将 FilePart 转换为 File 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2019-09-28
      • 2019-06-14
      • 1970-01-01
      相关资源
      最近更新 更多