如何模拟 URL 连接 [英] how to mock a URL connection
问题描述
我有一个方法可以将 URL 作为输入并确定它是否可访问.代码如下:
Hi I have a method that takes an URL as an input and determines if it is reachable. Heres the code for that:
public static boolean isUrlAccessible(final String urlToValidate) throws WAGNetworkException {
URL url = null;
HttpURLConnection huc = null;
int responseCode = -1;
try {
url = new URL(urlToValidate);
huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
} catch (final UnknownHostException e) {
throw new WAGNetworkException(WAGConstants.INTERNET_CONNECTION_EXCEPTION);
} catch (IOException e) {
throw new WAGNetworkException(WAGConstants.INVALID_URL_EXCEPTION);
} finally {
if (huc != null) {
huc.disconnect();
}
}
return responseCode == 200;
}
我想使用 PowerMockito
对 isUrlAccessible() 方法进行单元测试.我觉得我需要使用 whenNew()
来模拟 URL
的创建和调用 url.openConnection()
时,返回另一个模拟 HttpURLConnection
对象.但我不确定如何实现这一点?我在正确的轨道上吗?有人能帮我实现这个吗?
I want to unit test the isUrlAccessible() method using PowerMockito
. I feel that I will need to use whenNew()
to mock the creation of URL
and the when url.openConnection()
is called, return another mock HttpURLConnection
object. But I have am not sure how to implement this? Am I on the right track? Can anyone help me in implementing this?
推荐答案
找到了解决方案.首先模拟 URL 类,然后模拟 HttpURLConnection,当 url.openconnection() 被调用时,返回这个模拟的 HttpURLConnection 对象,最后将其响应代码设置为 200.代码如下:
Found the solution. First mock the URL class, then Mock the HttpURLConnection and when url.openconnection() is called, return this mocked HttpURLConnection object and finally set its response code to 200. Heres the code:
@Test
public void function() throws Exception{
RuleEngineUtil r = new RuleEngineUtil();
URL u = PowerMockito.mock(URL.class);
String url = "http://www.sdsgle.com";
PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.when(u.openConnection()).thenReturn(huc);
PowerMockito.when(huc.getResponseCode()).thenReturn(200);
assertTrue(r.isUrlAccessible(url));
}
这篇关于如何模拟 URL 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!