AccessTokenProvider { public <T> CompletableFuture<T> doWithToken(Function<? super AccessToken, ? extends CompletableFuture<T>> func) { return obtainAccessToken() .thenCompose(token -> func.apply(token) .whenComplete((result, exception) -> onRequestComplete(token, exception))); } AccessTokenProvider(SW360AuthenticationClient authClient); SW360AuthenticationClient getAuthClient(); CompletableFuture<T> doWithToken(Function<? super AccessToken, ? extends CompletableFuture<T>> func);  }
@Test public void testDoWithTokenFailedAccessToken() { Throwable expException = new IOException("Cannot obtain access token"); RuntimeException otherException = new RuntimeException("Function failed"); Function<AccessToken, CompletableFuture<Object>> func = token -> { throw otherException; }; CompletableFuture<String> tokenFuture = new CompletableFuture<>(); tokenFuture.completeExceptionally(expException); expectTokenRequest(tokenFuture); try { tokenProvider.doWithToken(func).join(); fail("No exception thrown!"); } catch (CompletionException ex) { assertThat(ex.getCause()).isEqualTo(expException); } }
@Test public void testDoWithTokenSuccess() { CompletableFuture<String> tokenFuture = CompletableFuture.completedFuture(TOKEN); Function<AccessToken, CompletableFuture<Object>> func = token -> CompletableFuture.completedFuture(token.getToken()); expectTokenRequest(tokenFuture); Object result = tokenProvider.doWithToken(func).join(); assertThat(result).isEqualTo(TOKEN); }