I checked Robolectric FakeHttpLayer and did not find a way to simulate an IOException throws.
So mock it to work for you. First enter HttpClientFactory (if you use HttpClient you can use the same approach for HttpUrlConnection ):
public class HttpClientFactory { public HttpClient createClient() { return new DefaultHttpClient(); } }
And now at your network level, use factory instead of constructors (for simplicity's sake, suppose it's synchronous):
public class HttpTransportLayer { private final HttpClientFactory clientFactory; public HttpTransportLayer() { this(new HttpClientFactory()); }
So, now you can use Mockito in the tests:
HttpClient mockedClient = mock(HttpClient.class); @Before public void setUp() { HttpClientFactory factory = mock(HttpClientFactory.class); when(factory.createClient()).thenReturn(mockedClient); target = new HttpTransportLayer(factory); } @Test public void whenIOExceptionThenReturnNull() { when(mockedClient.execute(any(HtptUriRequest.class))).thenThrow(new IOException()); String data = target.requestData("http://google.com"); assertThat(data).isNull(); }
This is a dummy test, and usually no one will return null in case of an error.
You can also look at some dependency injection infrastructure like Dagger to minimize injection code.
If you use any good network framework, such as Retrofit or Volley , then this is even easier - you donβt have to mock anything and just call the error callback.
Hope this helps
source share