You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WireMock单文件配置多存根失败问题求助

解决WireMock单个JSON文件整合多个存根的问题

你遇到的问题其实是因为Spring Boot集成WireMock时,对单个存根文件的格式要求和WireMock standalone模式有所区别。咱们一步步拆解原因和解决方案:

为什么之前的写法会报错?

  1. 带"mappings"键的JSON:这种格式是WireMock standalone模式下根目录mappings.json的格式,但Spring Boot的@AutoConfigureWireMock加载单个存根文件时,期望的是单个StubMapping对象,而不是包含mappings数组的容器对象,所以会抛出"Unrecognized field 'mappings'"的异常。
  2. 直接数组格式的JSON:Spring Boot自动配置会尝试把整个数组当成单个StubMapping实例来反序列化,自然会失败,抛出"Cannot deserialize instance of ... out of START_ARRAY token"的错误。

两种可行的解决方案

方案一:使用JSON Lines格式(推荐)

WireMock支持用JSON Lines格式在单个文件中存放多个存根——也就是每个StubMapping对象单独占一行,不需要用数组包裹。

举个例子,在classpath:/stubs/mappings/combined-stubs.json中写入:

{
  "request": {
    "method": "GET",
    "url": "/api/v1/users"
  },
  "response": {
    "status": 200,
    "body": "[{\"id\":1,\"name\":\"Alice\"}]"
  }
}
{
  "request": {
    "method": "POST",
    "url": "/api/v1/users"
  },
  "response": {
    "status": 201,
    "body": "{\"id\":2,\"name\":\"Bob\"}"
  }
}

你的测试类配置保持不变即可:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWireMock(port = 0, stubs = "classpath:/stubs/mappings", files = "classpath:/stubs")
public class ConfigurationTest {
    @Autowired
    protected WireMockServer wireMockServer;
}

WireMock会自动识别每一行作为独立的存根进行加载,不需要额外代码。

方案二:手动加载数组格式的存根

如果你坚持想用数组格式的JSON(比如[{"request": ...}, {...}]),可以通过手动加载的方式实现:

  1. 修改测试类,去掉@AutoConfigureWireMock中的stubs属性(避免自动加载引发冲突);
  2. 在@BeforeEach方法中读取数组格式的JSON文件,调用WireMockServer的批量加载方法。

示例代码:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWireMock(port = 0, files = "classpath:/stubs")
public class ConfigurationTest {
    @Autowired
    protected WireMockServer wireMockServer;

    @BeforeEach
    void loadCombinedStubs() throws IOException {
        // 读取数组格式的存根文件
        File stubFile = ResourceUtils.getFile("classpath:/stubs/mappings/all-stubs.json");
        String stubJson = Files.readString(stubFile.toPath());
        // 批量加载存根
        wireMockServer.loadMappingsFromJsonString(stubJson);
    }
}

这种方式需要自己处理文件读取,但能兼容你习惯的数组格式。

内容的提问来源于stack exchange,提问作者sewey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:47:25