java - 使用 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 请求进行单元测试的最佳方法是什么?
解决方案
我认为你有两个选择。
- 使间谍
BodyInserters.fromMultipartData
使用PowerMock
.PowerMock
可以为静态方法制作spy
/ 。mock
- 考虑使用 okhttp/mockwebserver( https://github.com/square/okhttp/tree/master/mockwebserver#recordedrequest )。它可以像下面的例子一样记录请求正文。
MockWebServer server = new MockWebServer();
RecordedRequest request = server.takeRequest();
assertEquals("{}", request.getBody().readUtf8());
推荐阅读
- c++ - 类中非静态数据成员的内存分配
- github - Github“解析 JSON 的问题”,在 Windows 10 上从控制台创建存储库
- javascript - 在Javascript中的数组内添加数组
- python - Pyinstaller exe非常大
- javascript - 检查瓷砖是否正在加载
- node.js - 使用 async/await 在 node.js 中使用 createReadStream
- jpa - 直接向 DTO 查询结果时出现语法错误
- node.js - Node.js 从文件中删除前 N 个字节
- html - 如何使用jQuery更改点击链接文本?
- sql-server - 关键字“into”附近的语法不正确,尝试创建视图时出现问题?