【问题标题】:Validate/Match JSON field for number and not string in the input request in Wiremock验证/匹配 Wiremock 输入请求中的数字而不是字符串的 JSON 字段
【发布时间】:2020-12-26 20:36:12
【问题描述】:

我正在尝试验证请求中的特定 json 字段 amount 是否包含数字而不是字符串

{
  "request": {
    "method": "POST",
    "urlPath": "/charges",
    "bodyPatterns" : [
      {"matchesJsonPath" : "$[?(@.amount =~ /^[0-9]*$/i)]"}
    ]
}

现在 request1 和 request2 工作正常, request3 失败。但我希望 request2 也会失败,因为它是一个字符串,而不是双引号中的数字。

请求 1,

{
    "amount": 123,
}

请求 2,

{
    "amount": "123",
}

请求 3,

{
    "amount": "a123",
}

这可能吗?我在 wiremock 文档中看到

    Since WireMock’s matching operators all work on strings, 
the value selected by the JSONPath expression will be coerced to a string before the match is evaluated.

【问题讨论】:

    标签: wiremock wiremock-standalone


    【解决方案1】:

    我找到了解决方法。

    根据您给出的正则表达式,我看到amount 字段不能有负值。

    所以在matchesJsonPath 中,做一个虚拟检查值是否大于或等于0。这将确保值 123 将起作用,但“123”将引发错误

    您甚至不再需要使用正则表达式。

    {
      "request": {
        "method": "POST",
        "urlPath": "/charges",
        "bodyPatterns" : [
          {"matchesJsonPath" : "$[?(@.amount >= 0)]"}
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多