I'm trying to mock for the same request URL (multiple times), with different responses according to the JSON Body content.
My Request JSON is build dynamically so I can't statically use the equalToJson
function on the Mock.
I have the same JSON like this:
{
// Changes according to the request
"task": "TEXT_ENTITY_RECOGNITION",
"category": "TEXT",
"data": content
}
What's the best approach for the wireMockServer
stubs?
I'm trying something like this
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)));
I have not found any sample of anything like this on the documentation. Thanks!
WireMock provides Several Content Pattern EqualToPattern and ContainsPattern are few of them. Try Something like :
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);
This works well for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With