java - 如何在 MockRestServiceServer 中验证 json 请求正文
问题描述
我的应用程序将各种模型序列化并通过 HTTP 请求将它们发送给第三方。
我想根据集成测试将请求正文反序列化为这个或那个模型,然后对其进行断言。看起来有些人可能会实现自己的RequestMatcher
,或者只是针对字符串断言,但这两个选项似乎都很脏。如果我实现了我自己的RequestMatcher
,我将不得不为RequestMatcher
身体可能的每个模型(并且有很多)实现一个不同的模型。
如果我可以反序列化请求正文中的 json 并在声明性匹配内容之外用它做我想做的事情,那就太好了。
像这样的东西:
BodyCaptor captor = new BodyCaptor(); // I made this up
MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
mockServer
.expect(MockRestRequestMatchers.requestTo(testBaseUri + testApiPath))
.andExpect(method(HttpMethod.POST))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andCaptureBody(captor)
.andRespond(MockRestResponseCreators.withSuccess());
MyModel mymodel = objectMapper.deserialize(captor.getValue())
assertThat(mymodel.getWhateverProperty()).isEqualTo(5)
....
这样的事情可能吗?我有哪些选择?
解决方案
您可以使用MockRestRequestMatchers.jsonPath验证属性以验证 json 属性及其值
mockServer
.expect(MockRestRequestMatchers.requestTo(testBaseUri + testApiPath))
.andExpect(method(HttpMethod.POST))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(MockRestRequestMatchers.jsonPath("$.property", Matchers.equalToIgnoringCase("value")))
.andRespond(MockRestResponseCreators.withSuccess());
推荐阅读
- r - 基于多个日期范围和多个列的切片以使用 R 格式化新数据帧
- recursion - 在递归函数中分配堆栈以计算字符串长度 MIPS
- python - 如何使用 ffmpeg 更快地将字节写入标准输入以创建具有不同帧的新视频
- android - Dalvik 是否创建堆栈来管理线程
- python - 如何在 BucketIterator 中迭代标记化的 pytorch Multi30k 数据集?
- javascript - 功能组件数组未按预期附加道具内容
- r - 在 R 中编写一个函数来求解普朗克方程
- matlab - 如何在 Matlab 中平滑图形的阴影部分
- node.js - Contenerized expressjs 应用程序无法访问 mongo 容器
- c# - Kestrel 没有为 https “使用” pfx 文件