码迷,mamicode.com
首页 > 其他好文 > 详细

WireMock之定义状态控制返回

时间:2015-07-19 01:24:29      阅读:508      评论:0      收藏:0      [点我收藏+]

标签:

 

WireMock之定义状态控制返回

定义操作习惯

可以定义一个场景,然后通过状态来控制每次请求返回的内容
基本语法,初始状态总是为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

 

WireMock之定义状态控制返回

标签:

原文地址:http://www.cnblogs.com/opama/p/4657943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!