WireMock-实现Http Server Mock用于单元测试

作者:聂勇 欢迎转载,请保留作者信息并说明文章来源!
九寨沟

前一篇文章”使用jetty实现Http Server Mock作单元测试”讲了用Jetty实现Http Server Mock来模拟依赖的外部HTTP服务系统,但如果需要更多的功能,如:区分GET和POST;匹配请求的URL;匹配Http Header;匹配请求内容等等。 实际研发的过程中这些功能都有可能会用到,如果还是用Jetty来实现,需要自己不停地动手去添砖加瓦,虽然有成就感,但在快速迭代的节奏下不一定有足够的时间去做这些。 这时我们需要一个现成的类库来满足我们这些需求,WireMock和MockServer都可以做到,这里只讲WireMock。

预备

业务示例代码

源码下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cn.aofeng.demo.jetty;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
/**
* 抓取页面内容。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HttpGet {
public String getSomeThing(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(3000);
urlConn.setRequestMethod("GET");
urlConn.connect();
InputStream ins = null;
try {
if (200 == urlConn.getResponseCode()) {
ins = urlConn.getInputStream();
ByteArrayOutputStream outs = new ByteArrayOutputStream(1024);
IOUtils.copy(ins, outs);
return outs.toString("UTF-8");
}
} catch (IOException e) {
throw e;
} finally {
IOUtils.closeQuietly(ins);
}
return null;
}
}

单元测试代码

源码下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cn.aofeng.demo.wiremock;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import cn.aofeng.demo.jetty.HttpGet;
/**
* {@link HttpGet}的单元测试用例。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HttpGetTest {
private HttpGet _httpGet = new HttpGet();
@Rule
public WireMockRule _wireMockRule = new WireMockRule(9191);
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
/**
* 用例:响应状态码为200且有响应内容。
*/
@Test
public void testGetSomeThing4Success() throws Exception {
// 设置Mock
String response = "Hello, The World!";
stubFor(get(urlEqualTo("/hello"))
.willReturn(aResponse()
.withStatus(200)
.withBody(response)));
String content = _httpGet.getSomeThing("http://localhost:9191/hello");
assertEquals(response, content);
}
/**
* 用例:响应状态码为非200。
*/
@Test
public void testGetSomeThing4Fail() throws Exception {
// 设置Mock
stubFor(get(urlEqualTo("/hello"))
.willReturn(aResponse()
.withStatus(500)
.withBody("Hello, The World!")));
String content = _httpGet.getSomeThing("http://localhost:9191/hello");
assertNull(content);
}
}

参考资料