如何在Wiremock中为JUNIT匹配精确的json - java

我正在使用Wiremock在Spring启动应用程序中模拟Junit的REST服务。我的问题是,我无法匹配多个匹配模式。

Junit.java

StringValuePattern pattern = WireMock.matching(".*");
givenThat(post(urlEqualTo("/softwares"))
    .withHeader("Content-Type", equalTo("application/json"))
    //TODO: Matching exact JSON body
    .withRequestBody(pattern)
    .willReturn(aResponse()
    .withStatus(201)
    .withHeader("Content-Type", "application/json")
    .withBody("{\"userId\":\"ID009\"}")));

以上代码段中,我使用(。*)进行匹配。它工作正常。但是,我需要匹配Wiremock映射文件夹中已部署JSON中的确切内容

"matchesJsonPath" : "$.name",
"matchesJsonPath" : "$.protocol",
"matchesJsonPath" : "$.website",
"matchesJsonPath" : "$.website.user",
"matchesJsonPath" : "$.website.urlpath",
"matchesJsonPath" : "$.website.userlist",
"matchesJsonPath" : "$.website.resources.friendsList"

样本Json-部署在Wiremock的映射文件夹中

{
  "request" : {
    "urlPath" : "/softwares",
    "method" : "POST",
    "basicAuthCredentials" : {"username" : "username", "password" : "password"},
    "headers" : {
      "Content-Type" : {
        "equalTo" : "application/json"
      }
    },
    "bodyPatterns" : [ {
      "matchesJsonPath" : "$.name",
      "matchesJsonPath" : "$.protocol",
      "matchesJsonPath" : "$.website",
      "matchesJsonPath" : "$.website.user",
      "matchesJsonPath" : "$.website.urlpath",
      "matchesJsonPath" : "$.website.userlist",
      "matchesJsonPath" : "$.website.resources.friendsList"
    } ]
  },

  "response" : {
    "status" : 201,
    "headers" : { "Content-Type" : "application/json"},
    "body": "{ \"userId\" : \"ID009\"}"
    }
}

参考方案

您应该尝试extending wiremock。

每当请求到来时,它将把请求转发到一个方法,在该方法中,您可以获取请求字符串,然后执行所有验证并返回/重新路由/拒绝请求。这是一个非常强大的功能。

这里有更多的例子
http://one.wiremock.org/extending-wiremock.html

Spring Boot如何在POST之后返回响应 - java

我想创建一个新客户并在创建客户后返回客户编号。客户编号必须是从50000开始的自动递增的唯一编号。到目前为止,我已经成功创建了一个客户,但是我不确定应该如何生成客户编号,将其保存到数据库中,并在触发POST时将其作为成功消息显示给用户。json下面是所需的响应;{ "customerNumber": "50002", …

春天的多属性文件 - java

我在spring中加载属性文件: <context:property-placeholder location="classpath:foo.properties"/> 但是,如果我尝试在另一个上下文文件中加载另一个文件,则会出现错误。 java大神给出的解决方案 如果您需要覆盖属性,则可以执行以下操作:<context…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

java.net.URI.create异常 - java

java.net.URI.create("http://adserver.adtech.de/adlink|3.0") 抛出java.net.URISyntaxException: Illegal character in path at index 32: http://adserver.adtech.de/adlink|3.0 虽然n…

Spring MVC拦截器映射问题 - java

我有这段XML:<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/statics/**" /> <bean class="com.company.website.servlet.StaticsHandlerIntercept…