Last Updated: November 21, 2017
· xaethos

Mocking URLConnection

To use get an URLConnection you must call openConnection() on an URL instance, which makes it very difficult to stub directly for testing purposes. However, you can use URL.setURLStreamHandlerFactory() to handle all requests and return mock connections.

Here is a sample Android unit test that creates a mock connection and handler, and loads a local resource file as the network response: