Created
September 27, 2012 05:06
-
-
Save xaethos/3792258 to your computer and use it in GitHub Desktop.
Mocking HttpURLConnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class URLRequestUnit extends InstrumentationTestCase | |
{ | |
private static final String API_URL = | |
"http://www.example.com/api/users"; | |
public void testHttpOkay() throws Exception { | |
MockURLStreamHandler handler = new MockURLStreamHandler(); | |
URL.setURLStreamHandlerFactory(handler); | |
UsersRequest request = new UsersRequest(); | |
List<Users> users = request.doRequest(); | |
// Assert connection is set up correctly | |
MockHttpURLConnection conn = handler.getConnection(); | |
assertEquals(API_URL, conn.getURL().toString()); | |
assertEquals("application/json", conn.getRequestProperty("Accept")); | |
// etc... | |
// Assert results are parsed correctly | |
assertEquals(3, users.size()); | |
// etc... | |
} | |
public class MockURLStreamHandler extends URLStreamHandler | |
implements | |
URLStreamHandlerFactory | |
{ | |
private MockHttpURLConnection mConnection; | |
public MockHttpURLConnection getConnection() { | |
return mConnection; | |
} | |
// *** URLStreamHandler | |
@Override | |
protected URLConnection openConnection(URL u) throws IOException { | |
mConnection = new MockHttpURLConnection(u); | |
return mConnection; | |
} | |
// *** URLStreamHandlerFactory | |
@Override | |
public URLStreamHandler createURLStreamHandler(String protocol) { | |
return this; | |
} | |
} | |
public class MockHttpURLConnection extends HttpURLConnection | |
{ | |
protected MockHttpURLConnection(URL url) { | |
super(url); | |
} | |
// *** HttpURLConnection | |
@Override | |
public InputStream getInputStream() throws IOException { | |
// Load file in res/raw/users.json of the test project | |
Resources res = getInstrumentation().getContext().getResources(); | |
return res.openRawResource(R.raw.users); | |
} | |
@Override | |
public void connect() throws IOException { | |
} | |
@Override | |
public void disconnect() { | |
} | |
@Override | |
public boolean usingProxy() { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment