CognitoIdentityProvider { @NonNull public Single<Optional<Cognito>> refreshCognitoToken() { return this.identityManager.getMe() .doOnSubscribe(disposable -> { Logger.debug(CognitoIdentityProvider.this, "Clearing the cached cognito token to refresh"); localCognitoTokenStore.persist(null); }) .<Optional<Cognito>>map(meResponse -> { if (meResponse != null && meResponse.getUser() != null) { Logger.debug(CognitoIdentityProvider.this, "Retrieve a valid token response"); final User user = meResponse.getUser(); return Optional.of(new Cognito(user.getCognitoToken(), user.getIdentityId(), user.getCognitoTokenExpiresAt())); } else { Logger.warn(CognitoIdentityProvider.this, "Failed to fetch a valid token"); return Optional.absent(); } }) .doOnNext(optionalCognito -> { if (optionalCognito.isPresent()) { localCognitoTokenStore.persist(optionalCognito.get()); }else { localCognitoTokenStore.persist(null); } }) .singleOrError(); } @Inject  CognitoIdentityProvider(@NonNull IdentityManager identityManager,
                                   @NonNull LocalCognitoTokenStore localCognitoTokenStore); @NonNull Single<Optional<Cognito>> prefetchCognitoTokenIfNeeded(); @NonNull Single<Optional<Cognito>> refreshCognitoToken(); @Nullable Cognito synchronouslyRefreshCognitoToken(); @NonNull Optional<Cognito> getCachedCognitoToken();  }
@Test public void refreshCognitoTokenThrowsException() { Mockito.when(identityManager.getMe()).thenReturn(Observable.<MeResponse>error(new IOException())); TestObserver<Optional<Cognito>> testObserver = cognitoIdentityProvider.refreshCognitoToken().test(); Mockito.verify(localCognitoTokenStore).persist(null); testObserver.assertNoValues() .assertNotComplete() .assertError(IOException.class); }
@Test public void refreshCognitoTokenReturnsNullUserResponse() { Mockito.when(meResponse.getUser()).thenReturn(null); Mockito.when(identityManager.getMe()).thenReturn(Observable.just(meResponse)); TestObserver<Optional<Cognito>> testObserver = cognitoIdentityProvider.refreshCognitoToken().test(); Mockito.verify(localCognitoTokenStore, Mockito.times(2)).persist(null); testObserver.assertValue(Optional.absent()) .assertComplete() .assertNoErrors(); }
@Test public void refreshCognitoTokenIsValid() { Mockito.when(identityManager.getMe()).thenReturn(Observable.just(meResponse)); Mockito.when(user.getCognitoToken()).thenReturn(TOKEN); Mockito.when(user.getIdentityId()).thenReturn(IDENTITY_ID); Mockito.when(user.getCognitoTokenExpiresAt()).thenReturn(EXPIRES_AT); final TestObserver<Optional<Cognito>> testObserver = cognitoIdentityProvider.refreshCognitoToken().test(); final Cognito cognito = new Cognito(TOKEN, IDENTITY_ID, EXPIRES_AT); Mockito.verify(localCognitoTokenStore).persist(null); Mockito.verify(localCognitoTokenStore).persist(cognito); testObserver.assertValue(Optional.of(cognito)) .assertComplete() .assertNoErrors(); }