Robolectric: simulate network error in test

How can I create the same exception as with a real connection error in robolectric tests?

I want the program to work if the network is currently unavailable. Is it possible to create the same exception for my HttpClient?

I already tried:

Robolectric.getFakeHttpLayer().interceptHttpRequests(false); // with real network to a non existent IP 

and

 WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(false); 

and

 Robolectric.addPendingHttpResponse(404, null); 

but not one of them causes the same reactions as a real loss of connection.

thanks

+2
source share
1 answer

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()); } // For tests only HttpTransportLayer(HttpClientFactory clientFactory) { this.clientFactory = clientFactory; } public String requestData(String url) { HttpClient client = factory.createClient(); ... } } 

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

+2
source

Source: https://habr.com/ru/post/1208045/


All Articles