问题描述
我会自己回答我的问题,但我对我的解决方案不满意,所以如果有现成的方便类/方法做同样的事情,请告诉我。
问题说明
我在单元测试中使用 Spring MockRestServiceServer 来模拟 REST 服务调用。我想快速访问模拟 REST 服务器的请求正文。通常用于记录或仅用于在调试期间进行评估。
使用上下文如下:
import org.springframework.test.web.client.MockRestServiceServer;
class MyTest {
@Test
void mytest() {
MockRestServiceServer mockServer = ...;
mockServer
.expect(MockRestRequestMatchers.method(HttpMethod.POST))
.andExpect(MockRestRequestMatchers.requestTo("http://mock.example.com/myservice"))
// The following method does not exist,it's what I'd like to have
.andCapture(body -> {
/* do something with the body */
log.info(body);
}) // the place for the Captor
.andRespond(MockRestResponseCreators.withSuccess("The mock response",MediaType.TEXT_PLAIN))
;
}
}
问题
是否有现成的类/方法可以提供这种现成的“andCapture(body -> {})
”功能?
解决方法
我目前最好的解决方案是这样的:
.andExpect(request -> {
final String body = ((ByteArrayOutputStream) request.getBody()).toString(StandardCharsets.UTF_8);
/* do something with the body */
log.info(body);
})
但是,我希望可能存在一种直接捕获请求正文的便捷方法。