Robolectric: simulate network error in test

萝らか妹 提交于 2019-12-04 16:44:40

I've checked Robolectric's FakeHttpLayer and haven't found way to simulate throwing an IOException.

So use mocking to make it working for you. First introduce HttpClientFactory (if you use HttpClient, you can use same approach for HttpUrlConnection):

public class HttpClientFactory {
    public HttpClient createClient() {
     return new DefaultHttpClient();
    }
}

And now in your networking layer use factory instead of constructors (let for simplicity assume that it is 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 in tests use Mockito:

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();
}

That is dummy test and usually nobody will return null in case of error.

You could also task look to some dependency injection framework like Dagger to minimise injection code.

If you use any good framework for networking like Retrofit or Volley then it is even simpler - you don't need to mock anything and just invoke you error callback.

Hope it helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!