Java WireMock:如何编程修改已注册的Stub
解决WireMock编程式修改已注册Stub的问题
核心问题在于getStubMapping()返回的是副本对象,并非WireMock内部维护的引用,直接修改它不会同步到服务器。需要借助WireMock官方API完成修改,以下是两种可行方案:
方案一:通过StubBuilder编辑(推荐)
利用StubMapping.buildUpon()方法从已有映射生成StubBuilder,修改配置后通过editStub()提交变更:
WireMockServer server;// 假设已完成配置、读取JSON映射并启动 @Test public void test(){ // 1. 获取目标StubMapping(替换为你的Stub ID) StubMapping existingMapping = this.server.getStubMapping("your-stub-id"); // 2. 从已有映射构建StubBuilder,修改响应内容 StubBuilder updatedStub = existingMapping.buildUpon() .withResponse( ResponseDefinitionBuilder.responseDefinition() // 复制原有响应的状态码、头等配置 .withStatus(existingMapping.getResponse().getStatus()) .withHeaders(existingMapping.getResponse().getHeaders()) // 修改JSON响应体:生成可修改的副本后调整字段 .withJsonBody( existingMapping.getResponse().getJsonBody() .deepCopy() .set("someValue", TextNode.valueOf("newValue")) ) ) .build(); // 3. 提交修改到WireMock服务器 this.server.editStub(updatedStub); // 执行测试... }
方案二:修改StubMapping后重新提交
若使用editStubMapping(),需确保修改的是可变更的副本配置,再提交完整映射:
WireMockServer server;// 假设已完成配置、读取JSON映射并启动 @Test public void test(){ StubMapping existingMapping = this.server.getStubMapping("your-stub-id"); // 创建响应定义副本,避免直接修改原对象 ResponseDefinition updatedResponse = ResponseDefinitionBuilder.responseDefinition() .from(existingMapping.getResponse()) // 复制原有响应配置 .withJsonBody( existingMapping.getResponse().getJsonBody() .deepCopy() .set("someValue", TextNode.valueOf("newValue")) ) .build(); // 更新StubMapping的响应配置 existingMapping.setResponse(updatedResponse); // 提交修改 this.server.editStubMapping(existingMapping); // 执行测试... }
关键注意点
- 禁止直接修改
getStubMapping()返回对象:WireMock内部维护独立副本,直接修改不会生效。 - 用
deepCopy()处理JSON体:WireMock的JSON节点默认不可变,必须生成副本后再修改。 - 保留原有配置:修改时需复制原有映射的请求匹配规则、响应状态码、头等信息,避免丢失配置。
内容的提问来源于stack exchange,提问作者Snappawapa
相关产品推荐
相关产品推荐

