I defined query parameter in my contract. I need this parameter to be optional:
method 'GET'
url($(regex(urlRegex))) {
queryParameters {
parameter 'fitler': $(stub(regex(filterRegex)))
}
}
I want this contract to be suitable for the both URLs with filter like /my/sample/url?fitler=some-filter-expression
and without the filter param like /my/sample/url
.
How can I achieve this? Is this even possible?
As query parameters are not a fixed part of a path, they can be optional and can have default values.
You can do it in three ways: Set required = false in @RequestParam annotation. Set defaultValue = “any default value” in @RequestParam annotation. Using Optional keyword.
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
So far, this has no explicit way defined in WireMock spec. However, you have a workaround using regex, by specifying the URL using urlPathPattern
property (in JSON stubbing). Refer to the example below.
{
"request": {
"method": "GET",
"urlPathPattern": "/myapp/users(\\?((a-zA-Z\\d\\_\\-)+\\=(a-zA-Z\\d\\_\\-)+)(\\&(a-zA-Z\\d\\_\\-)+\\=(a-zA-Z\\d\\_\\-)+)+)?"
},
"response": {
"status": 200,
"bodyFileName": "users.json",
"headers": {
"Content-Type": "application/json"
}
}
}
Observe the optional portion at the end of the URL, which looks for the typical URL query structure. This, I have tried out in wiremock and it runs smoothly.
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