0

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?

KDX2
  • 945
  • 2
  • 14
  • 31

1 Answers1

1

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.

agoff
  • 5,818
  • 1
  • 7
  • 20
  • Thank you a lot for the exhaustive response! For now I'm trying to avoid scenarios. I was sticking to managing all via priorities but as you say, I'll look up Response Transformer. The priorities route is a simple working suggestion here. Thanks! – KDX2 May 09 '20 at 10:46
  • 1
    No problem! I think avoiding scenarios is reasonable -- I try to do the same when possible. The priorities will work if you want something as simple as the example, but once things get a little more complicated, I'd recommend the response transformers, with the caveat that I recommend response transformers for almost anything. (Sometimes this is the right use and other times it is a little like using a jackhammer for a hanging a picture) – agoff May 11 '20 at 13:08