可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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; }
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?
回答1:
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)); }
回答2:
You can mock new Url instance with
whenNew(URL.class)..
Make sure you return a previously created mock object from that whenNew call.
URL mockUrl = Mockito.mock(URL.class); whenNew(URL.class).....thenReturn(mockUrl );
Then you can add behavior to your mock as you want.
回答3:
In order to mock java.net.URL class through mockito
library, you need to perform the following steps:
- Create a directory, named 'mockito-extensions' in src/tests/resources directory.
- Create text a text file in the folder, named org.mockito.plugins.MockMaker and put
mock-maker-inline
text into the file. - you can mock the class like the following:
code:
package myproject; import org.junit.Test; import java.net.HttpURLConnection; import java.net.URL; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class Test { @Test public void test() throws Exception { URL url = mock(URL.class); HttpURLConnection huc = mock(HttpURLConnection.class); when(url.openConnection()).thenReturn(huc); assertTrue(url.openConnection() instanceof HttpURLConnection); } }