Skip to content
Home » Verifying the Presence of a Property/Value Pair in a Request Body using WireMock and Java

Verifying the Presence of a Property/Value Pair in a Request Body using WireMock and Java

monochrome photo of man doing an inspection

WireMock is a powerful open source tool for testing and mocking HTTP services. It allows you to simulate different responses to HTTP requests and provides an easy-to-use API for verifying that certain requests have been made. One of the most common use cases for WireMock is to verify that a request body contains a specific property/value pair. See how to use WireMock to verify the presence of a property/value pair in a request body.

The first step in verifying the presence of a property/value pair is to set up a WireMock server. This is done using the WireMockServer class, which can be instantiated like so:

WireMockServer wireMockServer = new WireMockServer(options().port(8080));
wireMockServer.start();

Once the server is running, you can use the verify method to check if a request was made to a specific endpoint with a specific request body. The verify method takes a RequestPatternBuilder object, which can be used to specify the request URL, HTTP method, headers, and body.

To verify the presence of a property/value pair in the request body, you can use the withRequestBody method of the RequestPatternBuilder object. This method takes a ContentPattern argument representing the expected pattern, and uses a JSONPath to match if the expected property/value pair is present in the actual request body. For example:

String source = "my-source";
String processInstanceId = "123";
wireMockServer.verify(postRequestedFor(urlEqualTo("/cloud-event"))
                .withRequestBody(matchingJsonPath("$.id", equalTo(source + "_" + processInstanceId))));

In this example, we’re verifying that a POST request was made to the /cloud-event endpoint with a request body that contains an id property with a value of my-source_123.

Note that the matchingJsonPath method is case-sensitive, so it’s important to make sure that the expected property/value pair matches the case of the actual request body.

In conclusion, using WireMock to verify the presence of a property/value pair in a request body is a powerful way to test and mock HTTP services. By setting up a WireMock server and using the verify method with the withRequestBody method, you can easily check that your HTTP endpoints are receiving the expected data.