标签:
可以定义一个场景,然后通过状态来控制每次请求返回的内容
基本语法,初始状态总是为Started
XXX.inScenario("Scenario") .whenScenarioStateIs("Started") .willSetStateTo("NewStatus")); XXX.inScenario("Scenario") .whenScenarioStateIs("NewStatus")
json样例
{ "scenarioName": "Scenario", "requiredScenarioState": "STARTED", "request": { "method": "GET", "url": "/xxx" }, "response": { "status": 200, "body" : "xxxxxxxxxxxxxxx" } } { "scenarioName": "Scenario", "requiredScenarioState": "Started", "newScenarioState": "NewStatus", "request": { .... }
场景1,比如想让同一个接口调用多次,每次返回不同的值,较多见于重试逻辑
1 @BeforeClass 2 public void setUp() throws FileNotFoundException, IOException 3 { 4 WireMock.configureFor("127.0.0.1", 8080); 5 wireMockServer = new WireMockServer(wireMockConfig()); 6 log.info("START WIREMOCK"); 7 wireMockServer.start(); 8 } 9 10 public void setMyRule() 11 { 12 13 stubFor(post(urlEqualTo("/api/pod")).inScenario("podtest").whenScenarioStateIs("Started") 14 .willReturn(aResponse().withStatus(200).withBody("api add fail first")) 15 .willSetStateTo("step2")); 16 stubFor(post(urlEqualTo("/api/pod")).inScenario("podtest").whenScenarioStateIs("step2") 17 .willReturn(aResponse().withStatus(200).withBody("api add suc second"))); 18 } 19 20 21 @Test 22 public void testForMock() 23 { 24 25 26 setMyRule(); 27 String response=HttpUtil.post("http://127.0.0.1:8080/api/pod",""); 28 log.info("GET RESP:"+response); 29 response=HttpUtil.post("http://127.0.0.1:8080/api/pod",""); 30 log.info("GET RESP:"+response); 31 32 33 }
按照设定,第一次返回fail,第二次返回suc
[INFO ]23:38:17, [Class]MockCliTest, [Method]setUp, START WIREMOCK [INFO ]23:38:18, [Class]MockCliTest, [Method]testForMock, GET RESP:api add fail first [INFO ]23:38:18, [Class]MockCliTest, [Method]testForMock, GET RESP:api add suc second PASSED: testForMock
通过WireMock.resetAllScenarios()
或post空请求到http://<host>:<port>/__admin/scenarios/reset.
可以将场景的状态重置为初始的start状态
更多详情见http://wiremock.org/stateful-behaviour.html
标签:
原文地址:http://www.cnblogs.com/opama/p/4657943.html