Wiremock:同一URL和内容的多个响应?

rug*_*den 8 testing api integration-testing unit-testing wiremock

也在这里分享:https://github.com/tomakehurst/wiremock/issues/625

我正在编写集成测试来验证与REST API交互的应用程序是否正确处理了不成功的请求.为此,我想模拟GET请求两次到HTTP端点的场景.第一次,请求不成功,响应状态代码为500; 第二次,请求成功,响应状态代码为200.请考虑以下示例:

@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")));

}
Run Code Online (Sandbox Code Playgroud)

有没有办法避免第二个StubMapping覆盖第一个 - 确保第一次doSomething()发出请求,返回状态代码为500的响应,第二次返回状态代码为200的不同响应

Tom*_*Tom 12

这就是Scenarios功能的用途.

您需要将两个存根放入场景(即相同的场景名称),使第一个存根触发器转换到新状态,然后使第二个存根在场景处于第二状态且第一个存根取决于该场景处于该STARTED州.

请参阅:http://wiremock.org/docs/stateful-behaviour/


rug*_*den 11

使用场景功能,这样的事情有所帮助

// 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>")));
Run Code Online (Sandbox Code Playgroud)