Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WireMock - Stub for Request Containing JSON Attribute

Tags:

java

wiremock

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!

like image 775
Rodsnjr Avatar asked Oct 18 '25 10:10

Rodsnjr


1 Answers

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.

like image 137
RAJESH KUMAR Avatar answered Oct 20 '25 00:10

RAJESH KUMAR