### Question:
RequestRetryAuthenticator implements Authenticator { @Nullable @Override public Request authenticate(@NonNull Route route, @NonNull Response response) throws IOException { if (response.priorResponse() != null) { return null; } final String invalidAccessToken = parseHeaderAccessToken(response); final String token; if (invalidAccessToken.isEmpty()) { token = authenticator.getAccessToken(); } else { token = authenticator.getNewAccessToken(invalidAccessToken); } final String authorization = Headers.AUTH_BEARER + token; return response.request() .newBuilder() .removeHeader(Headers.AUTHORIZATION) .addHeader(Headers.AUTHORIZATION, authorization) .build(); } @Inject  RequestRetryAuthenticator(AccountAuthenticator authenticator); @Nullable @Override Request authenticate(@NonNull Route route, @NonNull Response response);  }### Answer:
@Test public void retryFailedRequestWithNewAuthToken() throws Exception { when(accountAuthenticator.getAccessToken()).thenAnswer(invocation -> invalidAccessToken); when(accountAuthenticator.getNewAccessToken(invalidAccessToken)) .thenAnswer(invocation -> validAccessToken); Request request = requestRetryAuthenticator.authenticate(null, response); assertNotNull(request); verify(accountAuthenticator, times(1)).getNewAccessToken(invalidAccessToken); Assert.assertEquals(request.headers("Authorization").size(), 1); Assert.assertEquals("Bearer " + validAccessToken, request.header("Authorization")); }
@Test public void stopRetryAfterFailedAttempt() throws Exception { when(accountAuthenticator.getAccessToken()).thenAnswer(invocation -> invalidAccessToken); when(accountAuthenticator.getNewAccessToken(invalidAccessToken)) .thenAnswer(invocation -> validAccessToken); Response secondResponse = response.newBuilder().priorResponse(response).build(); Request request = requestRetryAuthenticator.authenticate(null, secondResponse); assertNull(request); }
@Test public void retryWithNoPriorAuth() throws Exception { when(accountAuthenticator.getAccessToken()).thenAnswer(invocation -> validAccessToken); Response unauthenticatedResponse = response.newBuilder() .request( response.request() .newBuilder() .removeHeader("Authorization") .build()) .build(); Request request = requestRetryAuthenticator.authenticate(null, unauthenticatedResponse); assertNotNull(request); Assert.assertEquals("Bearer " + validAccessToken, request.header("Authorization")); }