tom*_*ato 8 java mockito okhttp
我正在尝试在 OkHttpClient 抛出 IOException 事件中测试我的代码库
待测代码
try (var response = okHttpClient.newCall(request).execute()) {
return response;
} catch (final IOException e) {
log.error("IO Error from API", e);
throw new ApiException(e.getMessage(), e);
}
Run Code Online (Sandbox Code Playgroud)
测试
@Test
void createCustomer_WhenValidRequestAndIOException_ThenThrowAPIException() throws ZeusServiceException, ZeusClientException {
//Given
final OkHttpClient okHttpClientMock = mock(OkHttpClient.class, RETURNS_DEEP_STUBS);
final OkHttpClient.Builder okHttpBuilderMock = mock(OkHttpClient.Builder.class);
httpClient = new HttpClient(okHttpClientMock, configuration, objectMapper);
//When
when(okHttpClientMock.newBuilder()).thenReturn(okHttpBuilderMock);
when(okHttpBuilderMock.build()).thenReturn(okHttpClientMock);
when(okHttpClientMock.newCall(any())).thenThrow(IOException.class);
final var result = httpClient.createCustomer(request);
assertThatThrownBy(() -> httpClient.createCustomer(request))
.isInstanceOf(ApiException.class)
.hasMessage("IO Error from API");
}
Run Code Online (Sandbox Code Playgroud)
我试图模拟OkHttpClientandBuilder类,但是 Builder 是最终的,mockito 无法模拟它。
在被测类的构造函数中,建议您通过调用 this 来创建一个新的 OkHttpClient 实例
this.okHttpClient = okHttpClient.newBuilder().build();
Run Code Online (Sandbox Code Playgroud)
我尝试围绕 OkHttpClient 创建一个包装器,但这也不起作用
public class OkHttpClientWrapper extends OkHttpClient {
private OkHttpClient okHttpClient;
public OkHttpClientWrapper(final OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
}
@Override
public OkHttpClient.Builder newBuilder() {
return new Builder(okHttpClient);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何强制 okhttpclient 抛出 IOException?
最后最好的解决方案是利用 OkHttpMockWebServer
https://github.com/square/okhttp/tree/master/mockwebserver
使用 MockWebserver 意外终止 HTTP 连接的场景会导致 IOException 场景
@Test
void createCustomer_WhenValidRequestAndServerTerminatesConnection_ThenThrowIOException() throws ZeusServiceException, ZeusClientException {
//Given
final CreateCustomerRequest request = CreateCustomerRequest.builder().build();
//When
mockWebServer.enqueue(new MockResponse()
.setBody(new Buffer().write(new byte[4096]))
.setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY));
assertThatThrownBy(() -> httpClient.createCustomer(request))
.isInstanceOf(IOException.class)
.hasMessage("unexpected end of stream");
}
Run Code Online (Sandbox Code Playgroud)
注意:本测试中使用 AssertJ 库
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |