AuthService implements Listenable<AuthService.Listener> { public void refreshToken(AuthToken token) { if (mbRequestOngoing) { return; } mbRequestOngoing = true; mApi.getConfiguration() .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .map(ConfigurationList::getClientSecret) .map(clientSecret -> new RefreshReqBody(token.getRefreshToken(), clientSecret)) .flatMap(mApi::refreshAuthToken) .doOnNext(authToken -> authToken.setRefreshToken(token.getRefreshToken())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleAuthToken, this::handleRefreshError); } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)  AuthService(String blogUrl, GhostApiService api,
                CredentialSource credSource, CredentialSink credSink); static AuthService createWithStoredCredentials(String blogUrl, GhostApiService api); static AuthService createWithGivenCredentials(String blogUrl, GhostApiService api,
                                                         CredentialSource credSource); @Override void listen(@NonNull Listener listener); @Override void unlisten(@NonNull Listener listener); void refreshToken(AuthToken token); void revokeToken(AuthToken token);  }
@Test public void refreshToken_expiredTokensAndAuthCode() { CredentialsExpiredEventListener spy = spy(new CredentialsExpiredEventListener()); getBus().register(spy); refreshToken("expired-access-token", "expired-refresh-token", "expired-auth-code"); verify(credSink).deleteCredentials(BLOG_URL); verify(spy).onCredentialsExpiredEvent(any()); getBus().unregister(spy); }
@Test public void refreshToken_expiredAccessToken() { refreshToken("expired-access-token", "refresh-token", "auth-code"); verify(credSink).setLoggedIn(BLOG_URL, true); verify(listener).onNewAuthToken(argThat(hasProperty("accessToken", is("refreshed-access-token")))); verify(listener).onNewAuthToken(argThat(hasProperty("refreshToken", is("refresh-token")))); }
@Test public void refreshToken_expiredAccessAndRefreshToken() { refreshToken("expired-access-token", "expired-refresh-token", "auth-code"); verify(credSink).setLoggedIn(BLOG_URL, true); verify(listener).onNewAuthToken(argThat(hasProperty("accessToken", is("access-token")))); verify(listener).onNewAuthToken(argThat(hasProperty("refreshToken", is("refresh-token")))); }