我正在尝试模拟相同的请求URL(多次),根据JSON Body内容使用不同的响应。
我的请求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)));
我没有在文档中找到任何类似的样本。谢谢!
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);
这对我很有用。