首页 > 解决方案 > 当没有请求匹配时,使用 WireMock 实现不同的响应

问题描述

我正在尝试存根 RESTful API。当(确实)找到资源时,其中一个资源返回详细信息,或者在最终没有给定 URL的资源时返回 HTTP 404( )。Not Found

这是我的简化存根/映射:

{
  "mappings": [
    {
      "name": "Retrieve Items",
      "request": {
        "headers": {
          "accept": {
            "caseInsensitive": true,
            "equalTo": "application/json"
          }
        },
        "method": "GET",
        "urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
      },
      "response": {
        "bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
        "headers": {
          "content-type": "application/json"
        },
        "status": 200
      }
    }
  ]
}

然后我有几个 JSON 文件(/home/wiremock/__files/items-api/responses/retrieve/用于匹配请求 - 但我找不到实现 HTTP 404( Not Found) 场景的方法:

{
  "timestamp": {{ now }},
  "status": 404,
  "error": "Not Found",
  "message": null,
  "path": "{{ request.path }}"
}

使用此配置,我从 WireMock 返回(预期的,但对我的用例没有用)响应,即uuid-sent-in-request.json找不到文件名。

目前有没有办法实现这种行为?

标签: wiremockwiremock-standalone

解决方案


目前,您需要编写 aResponseDefinitionTransformer来获得您正在寻找的行为。

它需要检查ResponseDefinition传入的参数是否需要文件,如果需要,则通过执行以下操作检查文件是否存在:

try {
    fileSource.getBinaryFileNamed(bodyFileName).readContents();
} catch (FileNotFoundException e) {
    return WireMock.notFound().withBody("custom body");
}

// Otherwise return the unmodified response definition

推荐阅读