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?
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.
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