我正在尝试模拟相同的请求URL(多次),根据JSON正文内容使用不同的响应。
我的请求JSON是动态构建的,因此无法静态使用Mock上的equalToJson
函数。
我有类似的JSON:
{
// Changes according to the request
"task": "TEXT_ENTITY_RECOGNITION",
"category": "TEXT",
"data": content
}
wireMockServer
存根的最佳方法是什么?
我正在尝试类似的事情
wireMockServer.stubFor(post(urlEqualTo("/request"))
.withRequestBody(containing("TEXT_ENTITY_RECOGNITION"))
.withHeader("Content-Type", equalTo("application/json"))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody(mockedJson)));
我没有在文档中找到任何类似这样的样本。 谢谢!
答案 0 :(得分:0)
WireMock提供了几种内容模式EqualToPattern和ContainsPattern很少。尝试类似的东西:
StringValuePattern urlPattern = new EqualToJsonPattern("/request", true, true);
MappingBuilder mappingBuilder = WireMock.post(new UrlPattern(urlPattern, false));
StringValuePattern requestBodyPattern = new ContainsPattern("TEXT_ENTITY_RECOGNITION");
mappingBuilder.withRequestBody(requestBodyPattern).withHeader("Content-Type", new EqualToJsonPattern("application/json", true, true));
ResponseDefinitionBuilder response = WireMock.aResponse().withBody("Successful Custom Body Response").withStatus(201).withHeader("Content-Type", "application/json");
mappingBuilder.willReturn(response);
wireMockServer.stubFor(mappingBuilder);
这对我来说很好。
答案 1 :(得分:0)
Wiremock 有包含函数,调用方式为 WireMock. contains
wireMockServer.stubFor(post(urlEqualTo("/request"))
.withRequestBody(WireMock.containing("TEXT_ENTITY_RECOGNITION"))
.withHeader("Content-Type", equalTo("application/json"))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody(mockedJson)));