首页 > 解决方案 > Wiremock - 第一次映射错误时重定向到代理

问题描述

我正在尝试使用 Wiremock 2.24.1 根据请求路径动态返回不同的主体文件,如果在本地找不到,我想调用外部资源(作为代理)。

我正在使用这个映射文件:

{
  "priority": 1,
  "request" : {
    "urlPattern" : "/rest/v2/name/.*",
    "method" : "GET"
  },
  "response" : {
    "status" : 200,
    "bodyFileName" : "rest_v2_name_{{request.requestLine.pathSegments.[3]}}_body.json",
    "headers" : {
      "Content-Type" : "application/json;charset=utf-8"
    },
    "transformers": ["response-template"]
  }
}

我有一个名为rest_v2_name_springfield_body.json的文件,里面有这个内容

[
    {
        "name": "Springfield",
        "now": "{{now}}",
        "yesterday"; "{{now offset='-1 days' format='yyyy-MM-dd HH:mm:ssZ'}},
        "tomorrow"; "{{now offset='1 days' format='yyyy-MM-dd HH:mm:ssZ'}}
    }
]

当我调用curl http://localhost:8099/rest/v2/name/springfield时返回:

[
    {
        "name": "Springfield",
        "now": "2019-08-17T00:23:12Z",
        "yesterday"; "2019-08-15 21:23:12-0300,
        "tomorrow"; "2019-08-17 21:23:12-0300
    }
]

如果我使用另一个路径值(如http://localhost:8099/rest/v2/name/brasil)调用,我希望由这个其他映射处理:

{
  "priority": 10,
  "request" : {
    "urlPattern" : "/rest/v2/name/.*",
    "method" : "GET"
  },
  "response" : {
    "proxyBaseUrl" : "http://restcountries.eu"
  }
}

但是,我没有回答http://restcountries.eu/rest/v2/name/brasil的响应,而是收到一条带有此消息的本地 HTTP 500 错误(我相信它来自第一个匹配映射):

java.io.FileNotFoundException: ./__files/rest_v2_name_brasil_body.json

我试过这个替代品

有没有办法在不编码的情况下解决这种情况?

标签: javaspring-bootproxystubwiremock

解决方案


无论代理如何on/off,Wiremock 都将始终遵循优先级。

考虑到您有相同的请求模式,

案例-I:当您拥有Proxy(brasil) at priority 1并且stub-mapping(spingfield) at priority 10:您将仅通过代理获得所有响应。其他映射类型的事情没有故障转移检查。

Case-I : 当你有Proxy(brasil) at priority 10and stub-mapping(spingfield) at priority 1: 你将得到与你配置的存根映射相同的响应,因为每个请求都将满足springfield规则。

为了解决这个问题,您需要在使用 Proxy 时记录每个请求。

停止录制后,您可以检查映射并根据需要添加其他映射!


推荐阅读