Wiremock: multiple answers for the same url and content?

Also shared here: https://github.com/tomakehurst/wiremock/issues/625

I am writing an integration test to make sure that my application that interacts with the REST API handles unsuccessful requests appropriately. For this, I want to simulate a scenario where GET requests are made twice at the HTTP endpoint. The first time a request is not executed with a response status code of 500; the second time the request was completed successfully with the response status code 200. Consider the following example:

@Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()
                                                               .dynamicHttpsPort());

@Test
public void testRetryScenario(){

// First StubMapping
stubFor(get(urlEqualTo("/my/resource"))
        .withHeader("Accept", equalTo("text/xml"))
        .willReturn(aResponse()
            .withStatus(500) // request unsuccessful with status code 500
            .withHeader("Content-Type", "text/xml")
            .withBody("<response>Some content</response>")));

// Second StubMapping
stubFor(get(urlEqualTo("/my/resource"))
        .withHeader("Accept", equalTo("text/xml"))
        .willReturn(aResponse()
            .withStatus(200)  // request successful with status code 200
            .withHeader("Content-Type", "text/xml")
            .withBody("<response>Some content</response>")));

//Method under test that makes calls to endpoint
doSomething();

Thread.sleep(5000);

//Verify GET request was made again after first attempt
verify(exactly(2), getRequestedFor(urlEqualTo("/my/resource")));

}

StubMapping - , doSomething() , 500, , 200?

+4
2

Scenarios .

( ), , , , stub, , STARTED.

: http://wiremock.org/docs/stateful-behaviour/

+7

- , Scenarios

// First StubMapping
stubFor(get(urlEqualTo("/my/resource"))
        .withHeader("Accept", equalTo("text/xml"))
        .inScenario("Retry Scenario")
        .whenScenarioStateIs(STARTED)
        .willReturn(aResponse()
            .withStatus(500) // request unsuccessful with status code 500
            .withHeader("Content-Type", "text/xml")
            .withBody("<response>Some content</response>"))
        .willSetStateTo("Cause Success")););

// Second StubMapping
stubFor(get(urlEqualTo("/my/resource"))
        .withHeader("Accept", equalTo("text/xml"))
        .inScenario("Retry Scenario")
        .whenScenarioStateIs("Cause Success")
        .willReturn(aResponse()
            .withStatus(200)  // request successful with status code 200
            .withHeader("Content-Type", "text/xml")
            .withBody("<response>Some content</response>")));
+1

Source: https://habr.com/ru/post/1671759/


All Articles