WireMock技术问题:如何将请求JSON体动态映射到响应体?
解决WireMock响应模板中
jsonPath helper找不到的问题 核心原因
你使用了错误的Helper名称:WireMock响应模板扩展中,JSONPath对应的Helper名称是json-path(短横线分隔),而非驼峰式的jsonPath,这直接导致系统找不到对应的Helper方法,抛出500错误。
分步解决方案
1. 修正响应模板中的Helper调用
将ResponsePayload.getResponseJsonPayload()中的jsonPath替换为json-path,同时修复JSON语法错误(移除对象末尾多余的逗号):
{ "response": "SUCCESS", "tokens": [ { "id": "{{json-path request.body '$.data[0].id'}}", "token": "xxxxxx" }, { "id": "{{json-path request.body '$.data[1].id'}}", "token": "xxxxxxx" } ] }
2. 修复测试代码中的语法错误
你的测试代码存在两处语法问题:
BeforeEach和AfterEach注解缺少@符号,导致生命周期方法无法执行tearDown()方法缺少闭合大括号
修正后的代码:
@SpringBatchTest class FileTest{ private WireMockServer wireMockServer; @BeforeEach void setUp() { wireMockServer = new WireMockServer(options() .extensions(new ResponseTemplateTransformer(true)) .port(PORT)); WireMock.configureFor("localhost", PORT); wireMockServer.start(); } @AfterEach void tearDown() { wireMockServer.stop(); } @Test void testEndToEndFlowForSpringBatch() { final String body = ResponsePayload.getResponseJsonPayload(); wireMockServer.addStubMapping( stubFor( post(urlPathMatching("/test")) .willReturn( aResponse() .withBody(body) .withStatus(200) .withTransformers("response-template")))); // 其他测试代码 } }
3. 确保依赖正确
如果使用Maven,确保引入包含响应模板扩展的WireMock依赖(推荐使用独立包避免依赖缺失):
<dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock-jre8-standalone</artifactId> <version>2.35.0</version> <scope>test</scope> </dependency>
如果使用Gradle:
testImplementation 'com.github.tomakehurst:wiremock-jre8-standalone:2.35.0'
4. 可选:动态生成tokens数组(适配任意数量的请求data)
如果请求中的data数组长度不固定,硬编码索引无法满足需求,可以使用Handlebars循环语法动态生成响应的tokens数组:
{ "response": "SUCCESS", "tokens": {{#each (json-path request.body '$.data')}} { "id": "{{this.id}}", "token": "固定的token值" }{{#unless @last}},{{/unless}} {{/each}} }
这个模板会自动遍历请求中data数组的每个元素,生成对应的tokens项,无需提前指定索引。
内容的提问来源于stack exchange,提问作者Zahid Khan
相关产品推荐
相关产品推荐

