Android 为okhttp超时写入单元测试
我已经为okHttpSocketTimeoutException编写了如下测试用例:Android 为okhttp超时写入单元测试,android,junit4,okhttp3,powermockito,mockserver,Android,Junit4,Okhttp3,Powermockito,Mockserver,我已经为okHttpSocketTimeoutException编写了如下测试用例: @Test public void contactDetailsTimeOut() throws Exception { server.enqueue(new MockResponse().setBody("{}").setBodyDelay(31, TimeUnit.SECONDS)); HttpUrl baseUrl = server.url("/v1/contact/")
@Test
public void contactDetailsTimeOut() throws Exception {
server.enqueue(new MockResponse().setBody("{}").setBodyDelay(31, TimeUnit.SECONDS));
HttpUrl baseUrl = server.url("/v1/contact/");
userProfilePresenter.contactDetails(baseUrl.toString());
verify(userProfileView).error(isA(SocketTimeoutException.class), isA(String.class));
}
通过将setSocketPolicy设置为SocketPolicy也可以实现同样的效果。无响应
@Test
public void contactDetailsTimeOut() throws Exception {
server.enqueue(new MockResponse().setBody("{}").setSocketPolicy(SocketPolicy.NO_RESPONSE));
HttpUrl baseUrl = server.url("/v1/contact/");
userProfilePresenter.contactDetails(baseUrl.toString());
verify(userProfileView).error(isA(SocketTimeoutException.class), isA(String.class));
}
因为我已经将okHttp读取超时设置为30秒。此测试用例等待30秒通过。预期的行为。下面是okHttpClient的代码
private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.build();
我的问题是:是否有任何方法可以在更短的时间内测试SocketTimeoutException?我不想减少客户端的计时。您可以在singleton模式中创建一个自定义OkHttpClient,然后您可以在单元测试中的setup()中准备它。是否有幸在更短的时间内测试它?@StuStirling否,我只是对此进行评论,并在需要时手动测试它。