java - 使用 WebtestClient 测试 MultipartFile

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

我正在为我的 Controller 类编写单元测试。我正在使用 spring webflux。因此我正在使用 WebTestClient 编写测试。这是我的 Controller 方法

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

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

"Required MultipartFile parameter 'file' is not present"

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

@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

最佳答案

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

必须更改 Controller 方法中的一些内容。当使用 Spring Web Flux(Reactive) 时,我们应该使用

1.@RequestPart 代替 @RequestParam
2. FilePart 代替 MultipartFile

所以 Controller 方法将如下所示。

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

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

关于java - 使用 WebtestClient 测试 MultipartFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395681/

相关文章:

Java播放错误的声音频率

java - 针对低性能硬件优化 spring boot

.net - 在解决方案中测试项目

javascript - 使用 ngMock 对外部站点进行无后端测试

perl - 有没有一种简单的方法可以为 perl 测试设置一个本地的、独立的 Web 服务器?

java - Mockito 测试具有调用网关服务步骤的方法

java - 并行测试时 TeamCity 中的构建日志令人困惑

java - 从 JavaFX 2.0 中的 TableView 读取多项选择

spring - 在Grails 3中使用Spring Boot Spring Security配置

java - Spring 启动 : accessing command line args from a bean