1 回答
TA贡献1943条经验 获得超7个赞
您可以通过存根ListeneableFuture并按CompletableFuture以下方式进行测试:
@Test
public void completeExceptionallyOnCallbackFailure() {
ListenableFuture<UserRecordResult> failureResponse = Futures.immediateFailedFuture(new RuntimeException());
CompletableFuture future = new CompletableFuture();
handleResponse(failureResponse, future);
assertThat(future.isCompletedExceptionally(), equalTo(true));
}
@Test
public void completeExceptionallyIfUserRecordResultIsNotSuccessful() {
UserRecordResult mockResult = Mockito.mock(UserRecordResult.class);
Mockito.when(mockResult.isSuccessful()).thenReturn(false);
ListenableFuture<UserRecordResult> failureResponse = Futures.immediateFuture(mockResult);
CompletableFuture future = new CompletableFuture();
handleResponse(failureResponse, future);
assertThat(future.isCompletedExceptionally(), equalTo(true));
}
@Test
public void completeSuccessfully() throws ExecutionException, InterruptedException {
UserRecordResult mockResult = Mockito.mock(UserRecordResult.class);
Mockito.when(mockResult.isSuccessful()).thenReturn(true);
ListenableFuture<UserRecordResult> successResponse = Futures.immediateFuture(mockResult);
CompletableFuture future = new CompletableFuture();
handleResponse(successResponse, future);
assertThat(future.get(), equalTo(true));
}
此外,您可以使用以下方法断言实际的错误消息assertj:
@Test
public void verifyMessageIfCompletedExceptionallyAfterUserRecordResultIsNotSuccessful() {
UserRecordResult mockResult = Mockito.mock(UserRecordResult.class);
Mockito.when(mockResult.isSuccessful()).thenReturn(false);
ListenableFuture<UserRecordResult> failureResponse = Futures.immediateFuture(mockResult);
CompletableFuture future = new CompletableFuture();
Assertions.assertThatThrownBy(() -> {
handleResponse(failureResponse, future);
future.get();
})
.isInstanceOf(Exception.class)
.hasMessage("java.lang.Exception: Fail to put record");
}
添加回答
举报