2017-03-08 56 views
4

也在這裏分享:https://github.com/tomakehurst/wiremock/issues/625Wiremock:對同一個URL和內容有多個響應?

我正在編寫一個集成測試,以驗證我的應用程序與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返回?

回答

6

這是場景功能的用途。

您需要將兩個存根都放到一個方案中(即相同的方案名稱),使第一個存根觸發器轉換到新的狀態,然後使第二個存根控制方案處於第二個狀態,第一個存根視情況而定,處於STARTED狀態。

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

+0

的感謝!這正是我需要的 – rugden

1

事情是這樣的幫助,使用場景功能

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