我正在 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 。
每当请求到来时,这会将请求转发到一个方法,在该方法中您可以获取请求字符串,然后执行所有验证并返回/重新路由/拒绝该请求。这是一个非常强大的功能。
关于java - 如何在 JUNIT 的wiremock 中匹配精确的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47986045/