Warm tip: This article is reproduced from stackoverflow.com, please click
wiremock

How to configure wiremock to send different responses (same url and requests) after reaching previou

发布于 2020-04-03 23:38:27

It is possible to configure wiremock to send different responses on same URL and same request after particular count of previous responses?

For example: 
1st request -> 503 response
2nd request -> 503 response
3rd request -> 503 response
4th request -> 200 response

This would simulate unavailable service during startup. And when it is up and running, then it responds 200 status.

Questioner
madafaka
Viewed
18
agoff 2020-01-31 22:58

You can achieve this using WireMock's Scenario feature. A potential set-up could be something like...

stubFor(get(urlEqualTo("/foo")).inScenario("Test Scenario")
    .whenScenarioStateIs(STARTED)
    .willReturn(aResponse().withStatus(503))
    .willSetStateTo("One Attempt"));
stubFor(get(urlEqualTo("/foo")).inScenario("Test Scenario")
    .whenScenarioStateIs("One Attempt")
    .willReturn(aResponse().withStatus(503))
    .willSetStateTo("Two Attempts"));
stubFor(get(urlEqualTo("/foo")).inScenario("Test Scenario")
    .whenScenarioStateIs("Two Attempts")
    .willReturn(aResponse().withStatus(200)));

In the above, you are setting up the Scenario by defining the scenario name and the initial behavior (all Scenarios begin in a state of STARTED.) After the first time running into the "/foo" endpoint, we return a 503 status, and the state of the Scenario is changed to "One Attempt". After the second time running into the "/foo" endpoint, we return a 503 status again, and the state of the Scenario is changed to "Two Attempts". If we hit the "/foo" endpoint again, we will return a 200 status, and not change the Scenario state.

One caveat is that you'll need to know the exact amount of times you'd like to return a specific status, so it won't allow you to return a 503 at random. But if you are certain you'll always need a specific amount of responses before just returning a 200, then scenarios should work.