Hon*_*dek 2 java spring unit-testing mocking mockrestserviceserver
我会自己回答我的问题,但我对我的解决方案不满意,所以如果有现成的便利类/方法做同样的事情,请告诉我。
我在单元测试中使用 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))
;
}
}
Run Code Online (Sandbox Code Playgroud)
是否有现成的类/方法可以提供andCapture(body -> {})开箱即用的“”功能?
到目前为止我最好的解决方案是这样的:
.andExpect(request -> {
final String body = ((ByteArrayOutputStream) request.getBody()).toString(StandardCharsets.UTF_8);
/* do something with the body */
log.info(body);
})
Run Code Online (Sandbox Code Playgroud)
但是,我希望可能存在一种直接捕获请求正文的便捷方法。
| 归档时间: |
|
| 查看次数: |
1353 次 |
| 最近记录: |