Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a request by size of array on root level in body

I am attempting to match a request by specifying jsonpath in a stub to match the request only if the body is an array of a given size.

This is an example of the code I am trying to make work.

@SpringBootTest
@AutoConfigureWireMock(port = 0)
public class WiremockTest {
    @Autowired
    private Environment env;

    @Test
    public void scenario() {
        stubFor(post(urlEqualTo("/test"))
                .withRequestBody(matchingJsonPath("$[?(@.size() == 1)]"))
                .willReturn(aResponse()
                        .withBody("{\"{{{jsonPath request.body '$.[0]'}}}\":\"value\"}")
                        .withTransformers("response-template")
                        .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)));
        var response = WebClient.create()
                .post().uri("http://localhost:%s/test".formatted(env.getRequiredProperty("wiremock.server.port")))
                .bodyValue("[\"key\"]")
                .retrieve().bodyToMono(String.class).block();
        System.out.println(response);
    }
}

When running this test, I get an error message on that the body does not match:

Closest stub       | Request
...
$[?(@.size() == 1] | ["key"] <<<<< Body does not match

I have tested with the jsonPathMatcher for non-root level arrays, and that seems to work, i.e:

$[?(@.array.size() == 1)]

when the body is

{
  "array": ["1"]
}

However, the requests I'm attempting to mock only has a root level array of strings.

Am I doing something incorrectly with the jsonPath?

like image 859
ODDminus1 Avatar asked Dec 05 '25 14:12

ODDminus1


1 Answers

Having fiddled a little more with this, I found a solution to be to change the JsonPath-expression to:

[?($.size() == 1)]

Instead of traversing into the root $ and using the element there @, I simply use the root directly in the expression.

like image 64
ODDminus1 Avatar answered Dec 07 '25 02:12

ODDminus1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!