WireMock如何在响应中保留请求整数字段类型及转换路径参数
WireMock响应中提取字段转为数字类型的解决方案
我正在评估将WireMock应用到项目中,需要实现从JSON请求里提取整数字段并以数字类型返回在响应中,同时也希望把从路径参数获取的id字段转为数字类型。
当前存根映射示例
String mapping = """ { 'request': { 'method': 'POST', 'urlPathTemplate': '/v1/persons/{personId}' }, 'response': { 'status': 200, 'jsonBody': { 'name' : "{{jsonPath request.body '$.name'}}", 'age' : "{{jsonPath request.body '$.age'}}", 'id' : '{{request.path.personId}}' }, 'headers': { 'Content-Type': 'application/json' } } } """;
发送的POST请求
POST http://localhost:8080/v1/persons/123456789 BODY: { 'name' : 'Alice', 'age' : 25 }
预期响应
{ "name" : "Alice", "age" : 25, "id" : 123456789 }
实际不符合预期的响应
{ "name" : "Alice", "age" : "25", "id" : "123456789" }
使用的Java代码(WireMock 3.9.1)
WireMockServer ws = new WireMockServer( wireMockConfig() .port(8080) .globalTemplating(true) ); ws.addStubMapping(StubMapping.buildFrom(mapping)); // 上述定义的映射字符串 ws.start(); var req = HttpRequest.newBuilder() .uri(new URI("http://localhost:8080/v1/persons/123456789")) .POST(HttpRequest.BodyPublishers.ofString(""" { 'name' : 'Alice', 'age' : 25 } """)).build(); var client = HttpClient.newHttpClient(); var resp = client.send(req, HttpResponse.BodyHandlers.ofString()); System.out.println("Got a body: " + resp.body()); ws.shutdownServer();
解决方案
要解决数字字段被转为字符串的问题,需要利用WireMock模板引擎的类型转换能力,同时移除字段值的引号(引号会强制将渲染后的数字转为字符串):
处理请求体中的age字段:在
jsonPath辅助函数中添加type='number'参数,直接将提取的值转为数字类型:'age' : {{jsonPath request.body '$.age' type='number'}}处理路径参数中的id字段:使用
number函数将字符串类型的路径参数转为数字类型:'id' : {{number request.path.personId}}
修改后的完整存根映射
String mapping = """ { 'request': { 'method': 'POST', 'urlPathTemplate': '/v1/persons/{personId}' }, 'response': { 'status': 200, 'jsonBody': { 'name' : "{{jsonPath request.body '$.name'}}", 'age' : {{jsonPath request.body '$.age' type='number'}}, 'id' : {{number request.path.personId}} }, 'headers': { 'Content-Type': 'application/json' } } } """;
修改后,响应中的age和id都会以数字类型返回,完全符合预期。
内容的提问来源于stack exchange,提问作者Mark Bramnik
相关产品推荐
相关产品推荐

