how to mock a URL connection

前端 未结 6 993
感情败类
感情败类 2020-12-06 01:50

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 Str         


        
6条回答
  •  情书的邮戳
    2020-12-06 02:17

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

提交回复
热议问题