依赖外部资源时解决方案-----存根

package stubbing;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class WebClient {
public String getContent(URL url) throws Exception {
StringBuffer content = new StringBuffer();

try {
URLConnection connection = url.openConnection();

connection.setDoInput(true);

InputStream is = connection.getInputStream();

byte[] buffer = new byte[2048];
int count;

while (-1 != (count = is.read(buffer))) {
content.append(new String(buffer, 0, count));
}

return content.toString();
} catch (Exception e) {
throw e;
}
}
}


当对这样的代码进行测试,可能想到的是部署一个服务器,如tomcat服务器,然后测试。

这种方案存在的缺点是:
必须保证外部环境在你之前运行。
测试被分割为了两部分。
难以完成自动化测试。


另一个推荐的方式则是在应用中内嵌一个小型的服务工具,如jetty。
jetty的解压目录如

[img]http://dl.iteye.com/upload/attachment/571683/b67042ec-5d96-3e89-81a7-e8b3458860ad.jpg[/img]

双击start.jar可以运行

如果要手动启动它的代码就像
public class JettySample {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
Context root = new Context(server, "/");
root.setResourceBase("./pom.xml");
root.setHandler(new ResourceHandler());
server.start();
}
}

如果要再test开始前启动它,可以这么写

package stubbing;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class TestWebClient {
@Before
public void setUp() {
// 按着刚才的代码启动jee容器
}

@After
public void down() {

}

@Test
public void testGetContent() throws MalformedURLException, Exception {
WebClient client = new WebClient();
String result = client.getContent(new URL("http://localhost:8080/"));
Assert.assertEquals(true,
0 < result.indexOf("<TITLE>Powered By Jetty</TITLE>"));
}
}


更好的例子是手动启动,并且写了一个处理器

package stubbing;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.jetty.HttpHeaders;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.util.ByteArrayISO8859Writer;

/**
* 实现一个jetty处理类,输出It works。
*
* @author liyixing liyixing1@yahoo.com.cn
* @version 1.0
* @since 2011-10-17 下午10:07:11
*/
public class TestGetContentOkHandler extends AbstractHandler {
public void handle(String arg0, HttpServletRequest arg1,
HttpServletResponse arg2, int arg3) throws IOException,
ServletException {
OutputStream out = arg2.getOutputStream();
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
writer.write("It works");
writer.flush();
arg2.setIntHeader(HttpHeaders.CONTENT_LENGTH, writer.size());
writer.writeTo(out);
out.flush();
}

}


package stubbing;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;

public class TestWebClient {
@BeforeClass
public void setUp() throws Exception {
Server server = new Server(8080);
Context contentOkContext = new Context(server, "/");
// 设置一个处理器
contentOkContext.setHandler(new TestGetContentOkHandler());
server.setStopAtShutdown(true);
server.start();
}

@AfterClass
public void down() {

}

@Test
public void testGetContent() throws MalformedURLException, Exception {
WebClient client = new WebClient();
String result = client.getContent(new URL("http://localhost:8080/"));
Assert.assertEquals("It works", result);
}
}

另一种方法是自己写一个实现了URL的代码,这个URL处理器只是输出一段话,而不是真正的连接到网络。

import java.net.URL;
import java.net.URLStreamHandlerFactory;
import java.net.URLStreamHandler;
import java.net.URLConnection;
import java.io.IOException;
public class TestWebClient1 {
@BeforeClass
public static void setUp() {
TestWebClient1 t = new TestWebClient1();
URL.setURLStreamHandlerFactory(t.new StubStreamHandlerFactory());
}
private class StubStreamHandlerFactory implements
URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
return new StubHttpURLStreamHandler();
}
}
private class StubHttpURLStreamHandler extends URLStreamHandler {
protected URLConnection openConnection(URL url)
throws IOException {
return new StubHttpURLConnection(url);
}
}
@Test
public void testGetContentOk() throws Exception {
WebClient client = new WebClient();
String result = client.getContent(new URL("http://localhost"));
assertEquals("It works", result);
}
}


import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
public class StubHttpURLConnection extends HttpURLConnection {
private boolean isInput = true;
protected StubHttpURLConnection(URL url) {
super(url);
}
public InputStream getInputStream() throws IOException {
if (!isInput) {
throw new ProtocolException(
"Cannot read from URLConnection"
+ " if doInput=false (call setDoInput(true))");
}
ByteArrayInputStream bais = new ByteArrayInputStream(
new String("It works").getBytes());
return bais;
}
public void disconnect() {}
public void connect() throws IOException {}
public boolean usingProxy() {
return false;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值