'In Wiremock I would like to return a 404 when a json file does not exist
In WireMock under the __files directory I have an invoices subdirectory. The number of json files in the directory changes over time.
To get an invoice I use the query like http://localhost:8080/invoices?getInvoice=81681. (The getInvoice value should match a json file in the invoices directory)
In my code I have the following stub:
stubFor(get(urlPathMatching("/invoices"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("invoices/{{request.query.getInvoice}}.json")
.withTransformers("response-template")));
When I make a request where query value matches a file in invoices I get a good response. When the request does not match I get a 500 response.
I would like to return a 404 instead of a 500. I looked for ways of having a conditional statement in my code but nothing I have tried so far works.
Solution 1:[1]
I believe the easiest way to accomplish this would be to have two separate stubs, one for the positive response (where the file exists) and one for the negative. We'll want to use priority to make sure we check the positive case before the negative.
The first stub below has a regex matcher for the getInvoices query parameter, currently only matching if the getInvoices value is 1234 or 5678. It will probably be easiest to maintain that as a variable you pull in instead of typing out a long matcher in line. Additionally, that stub has a priority of 1. Compare this to the second stub that has a priority of 5, and we can see that the first stub will always be checked before the second stub.
stubFor(get(urlPathMatching("/invoices"))
.withQueryParam("getInvoices", matching("(1234|5678)"))
.atPriority(1)
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("invoices/{{request.query.getInvoice}}.json")
.withTransformers("response-template")));
stubFor(get(urlPathMatching("/invoices"))
.atPriority(5)
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("invoices/404.json")
.withTransformers("response-template")));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | agoff |
