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

标签 java spring spring-boot junit wiremock

我正在 Spring boot 应用程序中使用wiremock 来模拟 Junit 的休息服务。我的问题是,我无法匹配多个匹配模式。

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"

Sample Json-which is deployed in wiremock's mapping folder

{
  "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

关于java - 如何在 JUNIT 的wiremock 中匹配精确的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47986045/

相关文章:

Spring Data MongoDB Repository - JPA 规范,如

mysql - Liquibase 无法在 MySQL 上添加非空、唯一、当前时间戳

java - 由 : org. h2.jdbc.JdbcSQLException 引起:数据转换错误转换

java - 如何在 Spring Boot 上返回 JSONObject?

Java - 如果之后定义了 actionPerformed,JButton 文本就会消失

java - Facebook 在 libGDX 中的实现

java - 如何为部署在 WildFly 9 中的应用程序设置 Log4j2?

java - 关闭应用程序时如何断开与设备的连接?

java - Spring Security如何检索用户名

java - Spring Data JPA - 订购者 : Sorting with Method Name vs Sort Class