Newer
Older
fedex-api / src / test / java / io / ljunggren / fedex / api / service / OauthServiceTest.java
package io.ljunggren.fedex.api.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Test;

import io.ljunggren.fedex.api.authorization.AuthToken;

public class OauthServiceTest {

    private final OauthService oauthService = new OauthService("https://example.com");

    @Test
    public void authorizeSuccessTest() throws Exception {
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse httpResponse = HttpTestUtils.mockResponse(200,
                "{\"access_token\":\"abc123\",\"token_type\":\"Bearer\",\"expires_in\":3600}");
        when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(httpResponse);

        AuthToken token = oauthService.authorize("clientId", "clientSecret", httpClient);

        assertEquals("abc123", token.getAccessToken());
        assertEquals(Integer.valueOf(3600), token.getExpiresIn());
        verify(httpClient).close();
    }

    @Test
    public void authorizePropagatesHttpFailureTest() throws Exception {
        CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
        when(httpClient.execute(any(HttpUriRequest.class))).thenThrow(new IOException("connection refused"));

        assertThrows(IOException.class, () -> oauthService.authorize("clientId", "clientSecret", httpClient));
        verify(httpClient).close();
    }

}