gpt4 book ai didi

java - MockRestServiceServer 中是否有现成的类来捕获请求正文以进行日志记录等?

转载 作者:行者123 更新时间:2023-12-03 08:26:22 26 4
gpt4 key购买 nike

我会自己回答我的问题,但我对我的解决方案不满意,所以如果有现成的便利类/方法做同样的事情,请告诉我。

问题陈述

我正在使用 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);
})

但是,我希望可能存在一种直接捕获请求正文的便捷方法。

关于java - MockRestServiceServer 中是否有现成的类来捕获请求正文以进行日志记录等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66549733/

26 4 0
文章推荐: javascript - 如何在javascript中合并子数组中的对象,以便在一个数组中留下多个对象
文章推荐: javascript - 如何加载带有关闭检查节点的jstree?
文章推荐: javascript - 如何在选择的数据加载之前显示进度条?
文章推荐: 使用
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com