Search code examples
testingmockingwiremockstubbingwiremock-standalone

Wiremock Return Success or Error Response from the same JSON Mapping


I am very new to Wiremock and even though I've went through the docs I still haven't wrapped my head around it completely.

What I'd like to find out is...

Is there a way to define in 1 stub two behaviours - a success response case and an error response (or multiple) case, in case e.g. the request's body-matching pattern was not satisfied? Is that supported or I should write separate request matchers for every type of invalid e.g. request body? Of course in a bit more generalized fashion.

If it's possible to combine error response and success response in the same stub JSON could you, please give me an example or point me to one as well?


Solution

  • The specific example (e.g. the request's body-matching pattern was not satisfied?) can easily be accomplished using two different stubs with two different priorities. The first stub would have a higher priority and be a more specific match and return the success response. The second stub would have a lower priority, essentially be a catchall for all other calls, and return the failure response.

    For example, if the only difference was that you wanted all calls to "/success-endpoint" to return a 200, and any other ones to return the 400...

    stubFor(get("/success-endpoint").atPriority(1)
        .willReturn(ok("Success response body")));
    
    stubFor(get(urlMatching("/.*")).atPriority(2)
        .willReturn(aResponse().withStatus(400).withBody("Error response body")));
    

    If you wanted to combine the success/error response in the same stub, you'd need to use a little more creativity. If the status code were in the request body, you could grab that using Response Template and plug it in as the response status code. If it weren't super visible and you needed to use something else in the request, you could create a Response Transformer and use that to inform your conditional response. Maybe Scenarios is something up your alley. Sorry that the rest of this response isn't super specific but instead sort of vague, but without knowing what your request/response looks like, there are a plethora of viable options.