WireMock 在使用 CustomHelper 时添加了意外字符

WireMock is adding unexpected character when using CustomHelper

我正在尝试使用自定义助手将 查询参数列表 从请求转换为 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 配置中注册了助手,如下所示:

@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"))
        );
    }
}

根据我的调试日志,助手的输出是有效的 JSON,类似于:

[{"score": 304,"userId": 10},{"score": 28,"userId": 20}]

但是当我尝试 运行 我的单元测试时,我从 JSON 解码器收到一条错误消息,指出我的响应包含意外的“&”字符。

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}}")[= 时使用“triple-mustaches”或“triple-stash” 12=]