junit4 使用LocalTestServer测试网络端口

单元测试只测试程序逻辑,不应该链接数据库等,但是有时候就是要测网络api怎么办?这里有一个比较简单粗暴的办法,就是使用LocalTestServer来在本地模拟一个server,然进行测试。

首先要设置一下pom.xml,加入

1
2
3
4
5
6
7
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.1</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>

在测试中,我们需要注册一个server,并且在server上绑定一个handle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//handle
HttpRequestHandler handler = new HttpRequestHandler() {
@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
httpResponse.setEntity(new StringEntity(respStr));
}
};
//server
public void setUp() throws Exception {
tpClient = ThridPartClient.getDefaultClient();
server = new LocalTestServer(null, null);
try {
server.start();
} catch (Exception e) {
throw new Exception("start new local test server error", e);
}
String url = "/Fetch";
server.register(url, handler);
}
//获得这个server的路径的方法
String baseUrl = "http://" + server.getServiceHostName() + ":" + server.getServicePort();

之后就可以在test里链接这个server了,无论是post还是get,只要你的参数完全匹配url,就会返回handle里写的respStr

如果你想拿到post的参数,可以在handle中用这种方法

1
2
3
4
5
6
7
8
9
10
11
12
HttpRequestHandler handler = new HttpRequestHandler() {
@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
if (httpRequest instanceof HttpEntityEnclosingRequest) { //if is post
HttpEntity entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
postParam = EntityUtils.toString(entity); //get postParam
} else {
postParam = null;
}
httpResponse.setEntity(new StringEntity(respStr));
}
};

本文采用创作共用保留署名-非商业-禁止演绎4.0国际许可证,欢迎转载,但转载请注明来自http://thousandhu.github.io,并保持转载后文章内容的完整。本人保留所有版权相关权利。

本文链接:http://thousandhu.github.io/2015/11/14/junit4-使用LocalTestServer测试网络端口/