如何模拟 URL 连接
嗨,我有一个方法,它将URL作为输入并确定它是否可访问。下面是该代码:
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;
}
我想使用 对 isUrlAccessible() 方法进行单元测试。我觉得我需要用它来模拟创建和调用时,返回另一个模拟对象。但是我不知道如何实现这一点?我是否在正确的轨道上?任何人都可以帮助我实现这一点吗?PowerMockito
whenNew()
URL
url.openConnection()
HttpURLConnection