如何在示例代码中模拟getContent()方法的HttpURLConnection,以及如何从模拟url获得响应
public class WebClient {
public String getContent(URL url) {
StringBuffer content = new StringBuffer();
try {
HttpURLConnection connection = createHttpURLConnection(url);
connection.setDoInput(true);
InputStream is = connection.getInputStream();
int count;
while (-1 != (count = is.read())) {
content.append(new String(Character.toChars(count)));
}
} catch (IOException e) {
return null;
}
return content.toString();
}
protected HttpURLConnection createHttpURLConnection(URL url) throws IOException{
return (HttpURLConnection)url.openConnection();
}
}
谢谢
发布于 2012-09-06 07:50:46
您的Webclient
为测试而设计得有点糟糕。您应该避免隐藏依赖项(基本上是大多数new
操作)。为了可模拟,这些依赖项应该(最好)在被测试对象的构造函数中被赋予,或者被测试对象应该将它们保存在一个字段中,这样它们就可以被注入。
或者,您可以像这样扩展您的Webclient
new Webclient() {
@Override
HttpURLConnection createHttpURLConnection(URL url) throws IOException{
return getMockOfURLConnection();
}
其中getMockOfURLConnection
从Mockito等模拟框架返回HttpURLConnection的模拟。然后,您将教会该模拟返回您想要的内容,并使用verify
检查它是否被正确调用。
发布于 2012-09-06 07:58:55
您应该重构您的代码:使用URL.openStream()方法,而不是这个转换为HttpURLConnection
。代码将更简单,更通用,更容易测试。
public class WebClient {
public String getContent(final URL url) {
final StringBuffer content = new StringBuffer();
try {
final InputStream is = url.openStream();
int count;
while (-1 != (count = is.read()))
content.append(new String(Character.toChars(count)));
} catch (final IOException e) {
return null;
}
return content.toString();
}
}
然后,您应该模拟URL
。这是最后一个类,所以你不能用Mockito来模仿它。它仍然有几种可能性,按偏好顺序排列:
在类路径中使用假资源测试
发布于 2012-09-06 07:42:54
为此,您需要使用存根,看看mockito.org它是一个易于使用的框架。这个想法是模仿类的行为,并验证您的代码是否处理积极和消极的情况。
https://stackoverflow.com/questions/12294987
复制相似问题