1

我正在尝试存根 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找不到文件名。

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

4

2 回答 2

1

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

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

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

// Otherwise return the unmodified response definition
于 2021-09-21T12:42:19.723 回答
1

汤姆的回答也可以。我认为他的解决方案的好处是它们不依赖于特定的请求 URL,但我的建议是为将与其特定 JSON 文件匹配的文件有一个特定的映射,并为不匹配的文件提供一个包罗万象的映射文件。通过为带有 JSON 响应的请求分配更高的优先级,WireMock 将首先检查这些请求,如果请求不匹配该映射中指定的任何值,则将继续检查第二个映射是否匹配,并返回 404。

{
  "mappings": [
    {
      "name": "Retrieve Items - Success",
      "priority": 1, // arbitrary number lower than the second priority
      "request": {
        "headers": {
          "accept": {
            "caseInsensitive": true,
            "equalTo": "application/json"
          }
        },
        "method": "GET",
        "urlPathPattern": "/api/items/(UUID1|UUID2|UUID3|UUID4)"
      },
      "response": {
        "bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
        "headers": {
          "content-type": "application/json"
        },
        "status": 200
      }
    },
    {
      "name": "Retrieve Items - 404 Not Found",
      "priority": 5, // arbitrary number that is higher than 1
      "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": {
        "status": 404
      }
    }
  ]
}
于 2021-09-21T13:12:14.143 回答