Robolectric:模拟测试中的网络错误

时间:2014-01-06 20:35:50

标签: unit-testing networking robolectric

如何在robolectric测试中发生真正的连接错误时产生相同的异常?

我想知道如果网络当前不可用,程序将如何起作用。是否有可能为我的HttpClient生成相同的异常?

我已经尝试过:

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

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

Robolectric.addPendingHttpResponse(404, null);

但是没有一个像真正的连接一样产生相同的反应。

谢谢

1 个答案:

答案 0 :(得分:2)

我检查了Robolectric的{​​{1}},但没有找到模拟投掷FakeHttpLayer的方法。

因此,使用模拟使其适合您。首先介绍IOException(如果您使用HttpClientFactory,则可以对HttpClient使用相同的方法):

HttpUrlConnection

现在在您的网络层使用工厂而不是构造函数(为简单起见假设它是同步的):

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

所以现在你可以在测试中使用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(); ... } }

Mockito

这是虚拟测试,通常没有人会在出错时返回null。

您还可以查看一些依赖注入框架,如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(); } ,以最大限度地减少注入代码。

如果您使用任何良好的网络架构,如DaggerRetrofit,那么它甚至更简单 - 您不需要模拟任何东西,只需调用错误回调。

希望有所帮助

相关问题