首页 > 解决方案 > 如何在 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)
....

这样的事情可能吗?我有哪些选择?

标签: javaspringspring-boot

解决方案


您可以使用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());

推荐阅读