2016-05-05 10 views
0

Ist es möglich, HttpURLConnection & URL-Objekt zu verspotten. Meine Einschränkung ist, dass ich PowerMockito nicht verwenden soll. Ich kann Mockito benutzen, aber Mockito sagt, dass URL nicht verspottet werden kann, da es der letzte Kurs ist.Mocking URL-Objekte in Java ohne PowerMockito

public static int getResponseCode(String urlString) 
     throws MalformedURLException, IOException 
{ 
    URL u = new URL(urlString); 
    HttpURLConnection huc = (HttpURLConnection)u.openConnection(); 
    huc.setRequestMethod("GET"); 
    huc.connect(); 
    return huc.getResponseCode(); 
} 

Antwort

0

bitte versuchen Sie es mit diesem

final URLConnection mockUrlCon = mock(URLConnection.class); 

ByteArrayInputStream is = new ByteArrayInputStream(
     "<myList></myList>".getBytes("UTF-8")); 
doReturn(is).when(mockUrlCon).getInputStream(); 

//make getLastModified() return first 10, then 11 
when(mockUrlCon.getLastModified()).thenReturn((Long)10L, (Long)11L); 

URLStreamHandler stubUrlHandler = new URLStreamHandler() { 
    @Override 
    protected URLConnection openConnection(URL u) throws IOException { 
     return mockUrlCon; 
    }    
}; 
URL url = new URL("foo", "bar", 99, "/foobar", stubUrlHandler); 
doReturn(url).when(mockClassloader).getResource("pseudo-xml-path"); 
+0

Was sind URLConnection und URLStreamHandler hier? – Ashley

1

Sie können eine Wrapper-Klasse erstellen, die eine URL wickelt und dann durch Standard Delegierten ruft seine Methoden auf eine tatsächliche URL-Implementierung.

ZB:

public class URLWrapper { 
    private URL url; 

    public URLWrapper(String urlString) { 
     this.url = new URL(urlString); 
    } 

    public HttpURLConnection openConnection() { 
     return this.url.openConnection(); 
    } 

    //etc 
} 

verwenden Jetzt URLWrapper in Ihrer Klasse statt URL direkt zu verwenden. URLWrapper kann jetzt leicht verspottet werden.