如何模拟 URL 连接

2022-09-03 06:22:27

嗨,我有一个方法,它将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() 方法进行单元测试。我觉得我需要用它来模拟创建和调用时,返回另一个模拟对象。但是我不知道如何实现这一点?我是否在正确的轨道上?任何人都可以帮助我实现这一点吗?PowerMockitowhenNew()URLurl.openConnection()HttpURLConnection


答案 1

找到解决方案。首先模拟 URL 类,然后模拟 HttpURLConnection,当调用 url.openconnection() 时,返回这个模拟的 HttpURLConnection 对象,最后将其响应代码设置为 200。代码如下:

@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));

    }

答案 2

您可以使用

whenNew(URL.class)..

确保从该当New 调用中返回以前创建的模拟对象。

URL mockUrl = Mockito.mock(URL.class);
whenNew(URL.class).....thenReturn(mockUrl );

然后,您可以根据需要向模拟添加行为。


推荐