### Question:
DefaultOAuth2TokenService extends AbstractOAuth2TokenService { @Override protected OAuth2TokenResponse requestAccessToken(URI tokenEndpointUri, HttpHeaders headers, Map<String, String> parameters) throws OAuth2ServiceException { HttpPost httpPost = createHttpPost(tokenEndpointUri, headers, parameters); return executeRequest(httpPost); } DefaultOAuth2TokenService();  DefaultOAuth2TokenService(@Nonnull CloseableHttpClient httpClient);  DefaultOAuth2TokenService(@Nonnull TokenCacheConfiguration tokenCacheConfiguration);  DefaultOAuth2TokenService(@Nonnull CloseableHttpClient httpClient,
			@Nonnull TokenCacheConfiguration tokenCacheConfiguration);   }### Answer:
@Test public void emptyResponse_throwsException() throws IOException { CloseableHttpResponse response = HttpClientTestFactory.createHttpResponse("{}"); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(response); assertThatThrownBy(() -> requestAccessToken(emptyMap())) .isInstanceOf(OAuth2ServiceException.class) .hasMessageContaining("expires_in"); }
@Test public void execute_yieldsTokenResponseWithCorrectData() throws IOException { CloseableHttpResponse response = HttpClientTestFactory.createHttpResponse(VALID_JSON_RESPONSE); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(response); OAuth2TokenResponse re = requestAccessToken(emptyMap()); assertThat(re.getAccessToken()).isEqualTo(ACCESS_TOKEN); assertThat(re.getRefreshToken()).isEqualTo(REFRESH_TOKEN); assertThat(re.getExpiredAt()).isAfter(Instant.now()); }
@Test public void executeWithAdditionalParameters_putsParametersIntoPostBody() throws IOException { ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); CloseableHttpResponse response = HttpClientTestFactory.createHttpResponse(VALID_JSON_RESPONSE); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(response); requestAccessToken(Maps.newHashMap("myKey", "myValue")); verify(mockHttpClient, times(1)).execute(httpPostCaptor.capture()); HttpPost httpPost = httpPostCaptor.getValue(); HttpEntity httpEntity = httpPost.getEntity(); assertThat(httpEntity).isNotNull(); String postBody = IOUtils.toString(httpEntity.getContent(), StandardCharsets.UTF_8); assertThat(postBody).contains("myKey=myValue"); }
@Test public void httpResponseWithErrorStatusCode_throwsExceptionContainingMessage() throws IOException { String unauthorizedResponseText = "Unauthorized!"; CloseableHttpResponse response = HttpClientTestFactory .createHttpResponse(unauthorizedResponseText, HttpStatus.SC_UNAUTHORIZED); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(response); assertThatThrownBy(() -> requestAccessToken(emptyMap())) .isInstanceOf(OAuth2ServiceException.class) .hasMessageContaining(unauthorizedResponseText) .hasMessageContaining(String.valueOf(HttpStatus.SC_UNAUTHORIZED)) .hasMessageContaining(TOKEN_ENDPOINT_URI.toString()); }