如何基于Spring Profile为Spring Boot的WireMock分环境配置响应延迟
解决Spring Boot中WireMock多Profile配置隔离(test/perf环境延迟区分)
下面提供三种无需单独搭建模拟服务的配置方案,按需选择:
方案1:按Profile加载独立的Stub配置文件
这是最直观的隔离方式,完全区分不同环境的Stub定义:
- 保持
test环境的Stub不变:放在src/test/resources/wiremock/mappings下,所有响应都不带延迟配置。 - 为
perf环境创建专属Stub目录:比如src/test/resources/perf/wiremock/mappings,将需要模拟延迟的Stub在此复制一份,并添加"fixedDelayMilliseconds": <目标毫秒数>参数。 - 通过Spring Profile切换配置路径:
在application-perf.properties中添加配置:
若使用WireMock Spring Boot Starter,启动时会自动识别激活的Profile,加载对应路径的Stub。wiremock.mappings-path=classpath:perf/wiremock/mappings
方案2:基于Profile动态给Stub添加延迟
如果不想复制大量Stub文件,可通过代码在启动时动态修改已有Stub:
- 创建WireMock配置类,根据激活的Profile判断是否添加延迟:
@Configuration public class WireMockConfig { @Bean public WireMockServer wireMockServer(Environment env) { WireMockServer server = new WireMockServer(WireMockConfiguration.options().port(9090)); server.start(); // 仅当perf Profile激活时添加延迟 if (Set.of(env.getActiveProfiles()).contains("perf")) { server.stubMappings().forEach(stub -> { // 给每个Stub的响应设置固定延迟,示例为500ms stub.getResponse().withFixedDelay(500); server.addStubMapping(stub); }); } return server; } }
- 若使用WireMock Spring Boot Starter,也可用自定义配置器实现:
@Component @Profile("perf") // 仅在perf环境生效 public class PerfWireDelayCustomizer implements WireMockConfigurationCustomizer { @Override public void customize(WireMockConfiguration config) { // 开启全局响应模板(可选,用于更灵活的延迟设置) config.globalResponseTemplating(true); // 直接设置全局默认延迟(对所有Stub生效) config.defaultResponseHeaders().addHeader("X-WireMock-Delay", "500"); } }
方案3:使用WireMock响应模板动态注入延迟值
适合需要灵活调整延迟数值的场景,通过Spring配置文件传递参数:
- 在不同Profile的配置文件中定义延迟值:
application-test.properties:wiremock.response.delay=0application-perf.properties:wiremock.response.delay=500
- 在Stub的响应配置中使用模板表达式引用该参数(需开启响应模板):
{ "request": { "method": "GET", "url": "/downstream/service" }, "response": { "status": 200, "body": "mock response", "fixedDelayMilliseconds": "{{properties.wiremock.response.delay}}" } } - 开启WireMock的响应模板功能:
在配置类或application.properties中添加:wiremock.global-response-templating=true
内容的提问来源于stack exchange,提问作者Ashutosh Sharma
相关产品推荐
相关产品推荐

