wiremock - 当没有请求匹配时,使用 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
找不到文件名。
目前有没有办法实现这种行为?
解决方案
目前,您需要编写 aResponseDefinitionTransformer
来获得您正在寻找的行为。
它需要检查ResponseDefinition
传入的参数是否需要文件,如果需要,则通过执行以下操作检查文件是否存在:
try {
fileSource.getBinaryFileNamed(bodyFileName).readContents();
} catch (FileNotFoundException e) {
return WireMock.notFound().withBody("custom body");
}
// Otherwise return the unmodified response definition
推荐阅读
- python - 数组作为张量流的输入
- discrete-mathematics - 我如何证明这个离散数学挑战?
- c# - macos 上的 CSC 没有列出 C# 9
- c - 如何在C中为二维数组的随机元素赋值
- reactjs - React:如何将值传递给我的主 App() 函数
- javascript - 如何从数据库中添加日期的月份并在网页中显示
- c++ - 哪个是在 C++ 中存储 1 个键和 2 个值的最佳数据结构
- python - 如何检查函数是否在python中返回一种类型的数据或另一种类型的数据
- ios - iOS上的德语蓝牙键盘字符错误
- spring - ibm rad 8, was 7, spring 3.2.9 和 xerces 问题