首页 > 解决方案 > 使用 WebClient 时对 POST 请求正文进行单元测试

问题描述

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

// 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();

在单元测试期间,我想测试条件是否正常工作。为此,我想通过某种方式验证请求正文是否有两个文件或只有一个文件。

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

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

标签: javaspringunit-testingwebclientspring-webflux

解决方案


我认为你有两个选择。

  1. 使间谍BodyInserters.fromMultipartData使用PowerMock. PowerMock可以为静态方法制作spy/ 。mock
  2. 考虑使用 okhttp/mockwebserver( https://github.com/square/okhttp/tree/master/mockwebserver#recordedrequest )。它可以像下面的例子一样记录请求正文。
MockWebServer server = new MockWebServer();
RecordedRequest request = server.takeRequest();
assertEquals("{}", request.getBody().readUtf8());

推荐阅读