使用Wiremock检查请求正文中的空值 [英] Check for null values in request body using Wiremock

查看:103
本文介绍了使用Wiremock检查请求正文中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个Wiremock存根,如果JSON有效负载中的任何字段为空值,该存根将返回400错误.基本上是模拟一个Bad Request.我一直在尝试使用匹配json键的任何小写字符串的正则表达式,但似乎不喜欢它.我找不到我想要的在线内容的任何示例,因此不确定是否可能.

I am trying to setup a wiremock stub that will return a 400 error if any field has a null value in the json payload. Basically to simulate a Bad Request. I've been trying with a regex that matches any lowercase string for the json key but it doesn't seem to like it. I can't find any examples of what I want online so not sure if it's even possible.

我的错误请求正文:

{
  "cat": null,
  "dog": {
    "id": 1344
},
  "horse": {
    "id": 1
},
  "fish": 1
}

我的存根:

wireMockServer.stubFor(post(urlEqualTo("/sample-api"))
            .withRequestBody(matchingJsonPath("$.^[a-z]*", equalTo(null)))
            .willReturn(aResponse()
                    .withStatus(400)
                    .withHeader("Content-Type", "application/json")))

在此示例中,我希望存根匹配"cat",因为它的值为null.事实并非如此.谁能告诉我我在做什么错?

In this example I would expect the stub to match "cat" as the value of it is null. This isn't the case. Can anyone tell me what I'm doing wrong?

推荐答案

WireMock文档中,请求匹配 源代码,其中引用了所使用的 com.jayway.jsonpath.JsonPath 库. build.gradle 指的是版本2.4.0.Jayway JSON路径库的文档可以在其 Github项目页面中找到.有一个很好的,但绝不是完美的在线评估者这里.

In the WireMock documentation on Request Matching the section on JSON Path matching. In the source code there is a reference to com.jayway.jsonpath.JsonPath library used. The build.gradle refers to version 2.4.0. The documentation for the Jayway JSON Path library can be found on their Github project page. There is a good, but by no means perfect online evaluator here.

WireMock文档仅以" matchesJsonPath ".Jayway文档中有一个在线示例:

The WireMock documentation only shows support for Regular Expression for the node values in the form of the "matchesJsonPath". In the Jayway documenatation there is an online example: $..book[?(@.author =~ /.*REES/i)]. For this reason the only approach is to name all the nodes that are not allowed to be null.

在下面的示例映射中,无论深度如何,所有提到的节点都将进行测试(请参阅@id).如果所有提及的节点都不为空,但某些未提及的节点为null,则不会触发此映射.

In the below example mapping all the mentioned nodes will be tested, regardless of their depth (see @id). This mapping will not trigger if all the mentioned nodes are not null, but some unmentioned ones are.

{
  "request": {
    "urlPattern": "/sample-api",
    "method": "GET",
    "bodyPatterns" : [ {
      "matchesJsonPath" : "$..[?(@.cat == null || @.dog == null || @.horse == null || @.fish == null || @.id == null)]"
    } ] 
  },
  "response": {
    "status": "400",
    "headers": {
      "Content-Type": "application/json; charset=utf-8"
    },
    "jsonBody": {
      "message": "some sapi message"
    }
  }
}

这篇关于使用Wiremock检查请求正文中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆