问题描述
我正在尝试使用自定义帮助程序将 查询参数 列表从请求转换为 JSON 响应。该请求类似于 /scores?userIds=1&userIds=2
,我想要的响应是一个 JSON 对象列表,如下所示:
[
{
"userId": 1,"score": 80
},{
"userId": 2,"score": 200
}
]
为此,我实现了一个名为 userscoreHelper
的助手:
Helper<List<String>> userscoreHelper = (context,options) -> {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
context.forEach(element ->
stringBuilder
.append("{\"score\": ")
.append(RandomGeneratorUtility.generaterandomNumber(0,700) - 1)
.append(",\"userId\": ")
.append(element)
.append("},")
);
stringBuilder
.deleteCharat(stringBuilder.lastIndexOf(","))
.append("]");
log.debug("Json response: {}",stringBuilder.toString());
return stringBuilder.toString();
};
然后我在我的 wiremockServer
配置中注册了 helper,如下所示:
@Bean(initMethod = "start",destroyMethod = "stop")
@Rule
public wiremockServer mockServer() {
return new wiremockServer(
options()
.port(9561)
.extensions(new ResponseTemplateTransformer(false,"user-score-helper",userscoreHelper))
);
}
我的存根配置如下:
public class ScoringCommunicatorMocks {
public static void setupMockScoringCommunicatorResponse(wiremockServer mockService) {
mockService.stubFor(
wiremock.get(wiremock.urlPathEqualTo("/scores"))
.willReturn(wiremock.aResponse()
//Using the registered handlebars helper here
.withBody("{{user-score-helper request.query.userIds}}")
.withHeader("Content-Type","application/json")
.withStatus(200)
.withTransformers("response-template"))
);
}
}
根据我的调试日志,helper 的输出是一个有效的 JSON,如下所示:
[{"score": 304,"userId": 10},{"score": 28,"userId": 20}]
但是当我尝试运行单元测试时,我收到来自 JSON Decoder 的错误消息,指出我的响应包含意外的“&”字符。
feign.codec.DecodeException: JSON conversion problem: Unexpected character ('&' (code 38)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('&' (code 38)): was expecting double-quote to start field name
at [Source: (pushbackinputstream); line: 1,column: 2] (through reference chain: java.util.ArrayList[0])
我怀疑 wiremock 存在转义 " 字符的问题,因为如果我像这样将生成的 JSON 对象直接放在正文中 .withBody("[{\"score\": 304,\"userId\": 10},{\"score\": 28,\"userId\": 20}]")
它只是完美地工作。
这是一种非常奇怪的行为,我不知道如何更深入地了解此错误的根本原因(堆栈跟踪的其余部分无关紧要,并且对我在此处已经陈述的内容没有任何帮助)。
非常感谢任何指针或解决方案。
解决方法
当我写完这个问题时,我实际上已经设法弄清楚出了什么问题。这确实是转义字符的问题,我需要做的就是在调用助手时使用“三重胡须”或“三重藏匿处”.withBody("{{{user-score-helper request.query.userIds}}}")
而不是 .withBody("{{user-score-helper request.query.userIds}}")
>