我的应用程序序列化了各种模型,并通过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());