我使用 Spring Cloud Contracts 创建了一些映射。我定义了两个合约,它们在请求部分基本相同,它们具有相同的 url 路径,但其中一个定义了查询参数。
当我在消费者端使用 WireMock 运行集成测试时,问题就出现了。 Wiremock 正在正确加载两个生成的映射,但是当我发送带有查询参数的请求时,将返回与不带查询参数的映射相对应的响应。
在此之后,我将 1 的优先级添加到更具体的一个(带有查询参数),并将 2 的优先级添加到另一个,现在按预期工作,但老实说,该解决方案是本能的,我不明白为什么有效。
就像优先级在条件中的优先级高于查询参数一样,对我来说这是不合逻辑的。查询参数应该是一个更好的鉴别器。
更具体的映射:
{
"id" : "413e922d-f92d-4a2c-8b2a-56dff17e7c4c",
"request" : {
"urlPath" : "/fetch-recommendations",
"method" : "PUT",
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
},
"queryParameters" : {
"exclusions" : {
"equalTo" : "Platformer"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['userId'] =~ /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/)]"
}, {
"matchesJsonPath" : "$.['preferredGenres'][?(@ == 'Platformer')]"
}, {
"matchesJsonPath" : "$.['preferredGenres'][?(@ == 'Stealth')]"
}, {
"matchesJsonPath" : "$.['preferredGenres'][?(@ == 'Adventure')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"videogames\":[{\"name\":\"Red Dead Redemption\",\"genre\":\"Adventure\"}]}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template", "spring-cloud-contract" ]
},
"uuid" : "413e922d-f92d-4a2c-8b2a-56dff17e7c4c",
"priority" : 1
}
没有查询参数的:
{
"id" : "49330cf5-7065-4c93-959d-a333ab855aa5",
"request" : {
"urlPath" : "/fetch-recommendations",
"method" : "PUT",
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['userId'] =~ /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/)]"
}, {
"matchesJsonPath" : "$.['preferredGenres'][?(@ == 'Platformer')]"
}, {
"matchesJsonPath" : "$.['preferredGenres'][?(@ == 'Stealth')]"
}, {
"matchesJsonPath" : "$.['preferredGenres'][?(@ == 'Adventure')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"videogames\":[{\"name\":\"Red Dead Redemption\",\"genre\":\"Adventure\"},{\"name\":\"Crash Bandicoot 3\",\"genre\":\"Platformer\"}]}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template", "spring-cloud-contract" ]
},
"uuid" : "49330cf5-7065-4c93-959d-a333ab855aa5",
"priority" : 2
}
总而言之,WireMock 中映射的匹配标准是如何工作的?
WireMock 不会选择完全匹配的映射。就我而言,从映射角度来看,两种映射都匹配(是的,比其他映射多一个)。
因此,这里的决定性点是加载映射的顺序,选择匹配映射列表中第一个遇到的映射。
为了更好的解释和例子,请检查这个答案: https://stackoverflow.com/a/62381321/8600439