Java 在使用WebClient时对请求正文进行单元测试

Java 在使用WebClient时对请求正文进行单元测试,java,spring,unit-testing,webclient,spring-webflux,Java,Spring,Unit Testing,Webclient,Spring Webflux,下面是我向服务器发送多部分请求的代码片段。 根据某些条件,它决定只发布一个文件或同时发布两个文件 // Based on some condition add 1 or 2 files to the multipart body MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); if (postBothFiles) { parts.add("File_ONE", new FileS

下面是我向服务器发送多部分请求的代码片段。 根据某些条件,它决定只发布一个文件或同时发布两个文件

// Based on some condition add 1 or 2 files to the multipart body
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
if (postBothFiles) {
    parts.add("File_ONE", new FileSystemResource(file1));
}
parts.add("File_TWO", new FileSystemResource(file2));


// Perform the post request adding `parts` to the body
webClient.post().uri("/postUrl")
                .contentType(MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData(parts))
                .retrieve()
                .bodyToMono(String.class)
                .block();
//根据某些条件向多部分正文添加1或2个文件
MultiValueMap parts=新链接的MultiValueMap();
if(postBothFiles){
添加(“File_ONE”,新文件系统资源(file1));
}
添加(“File_TWO”,新的FileSystemResource(file2));
//执行post请求,在正文中添加'parts'
webClient.post().uri(“/postrl”)
.contentType(多部分表单数据)
.body(BodyInserters.fromMultipartData(parts))
.retrieve()
.bodyToMono(String.class)
.block();
在单元测试期间,我想测试条件是否正常工作。为此,通过某种方式,我想验证请求主体是否有两个文件或只有一个文件

我尝试使用
ExchangeFilterFunction
,但它不允许我阅读正文内容


单元测试此类POST请求的最佳方法是什么?

我认为您有两种选择

  • 使用
    PowerMock
    从MultipartData对BodyInserters
    PowerMock
    可以使
    spy
    /
    mock
    成为静态方法
  • 考虑使用okhttp/mockwebserver()。它可以记录请求主体,如下面的示例所示
  • MockWebServer server = new MockWebServer();
    RecordedRequest request = server.takeRequest();
    assertEquals("{}", request.getBody().readUtf8());