首页 > 解决方案 > 对同一个补丁请求端点使用 stubby 多个响应

问题描述

这是我在 data.yaml 中的补丁请求映射

request:
    url: ^/api/test
    method: PATCH
    headers:
      Content-Type: application/json 

  response:
    headers:
      Content-Type: application/json
    status: 200
    file: response/test-1.json

api 路径 api/test 是一个 PATCH 请求,它在其主体 {testVar: "1111"} 中接受单个请求参数

我需要实现的是当请求参数为 {testVar: "1111"} -> 请求参数为 {testVar: "2222"} 时调用 response/test-1.json -> 调用 response/test-2.json

如何实施?

我尝试了查询参数、请求参数等,但没有运气

标签: javascriptmockingyamlstubbingstubby4j

解决方案


阅读:

  1. https://stubby4j.com/docs/http_endpoint_configuration_howto.html#dynamic-token-replacement-in-stubbed-response。更具体地说,以下部分在哪里指定模板
  2. 另外,请查看以下 YAML,它是我的功能测试套件的一部分:https ://github.com/azagniotov/stubby4j/blob/master/src/functional-test/resources/yaml/include-regex-dynamic -tokens-templated-stubs.yaml#L13

这里的想法是:

在您的POST/PATCH请求负载中,您可以将参数之一指定为正则表达式,例如:{"testVar": "(.*)"}. 匹配时正则表达式的标记(即: 的值(.*))可以用作response配置的替换标记。换句话说,您应该能够根据需要加载相应的 JSON 文件。

但是,为了让您更轻松一些,请尝试以下 YAML 配置:

- request:
    method: PATCH
    url: ^/api/test
    headers:
      content-type: application/json
    post: >
      {"testVar": "(.*)"}

  response:
    headers:
      content-type: application/json
    status: 200
    file: response/test-<% post.1 %>.json

让我知道以上内容是否适合您。作为参考,我在以下 PR 中测试了上述配置:https ://github.com/azagniotov/stubby4j/pull/280


推荐阅读