Skip to content

Instantly share code, notes, and snippets.

@xaethos
Created September 27, 2012 05:06
Show Gist options
  • Save xaethos/3792258 to your computer and use it in GitHub Desktop.
Save xaethos/3792258 to your computer and use it in GitHub Desktop.
Mocking HttpURLConnection
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