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

时间:2017-03-08 00:49:58

标签: api unit-testing testing integration-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")));

}

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

2 个答案:

答案 0 :(得分:12)

这就是Scenarios功能的用途。

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

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

答案 1 :(得分:2)

使用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>")));