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

import static org.junit.Assert.assertEquals;
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.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

import io.ljunggren.ups.api.model.AuthToken;

public class OauthServiceTest {

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

    private CloseableHttpResponse mockResponse(String body) throws IOException {
        CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
        StatusLine statusLine = mock(StatusLine.class);
        when(statusLine.getStatusCode()).thenReturn(200);
        when(mockResponse.getStatusLine()).thenReturn(statusLine);
        HttpEntity entity = mock(HttpEntity.class);
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
        when(mockResponse.getEntity()).thenReturn(entity);
        return mockResponse;
    }

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

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

        assertEquals("abc123", token.getAccessToken());
        assertEquals("Bearer", token.getTokenType());

        ArgumentCaptor<HttpPost> captor = ArgumentCaptor.forClass(HttpPost.class);
        verify(httpClient).execute(captor.capture());
        Header[] headers = captor.getValue().getAllHeaders();
        assertEquals("x-merchant-id", headers[0].getName());
        assertEquals("accountNumber", headers[0].getValue());
        assertEquals("content-type", headers[1].getName());
        assertEquals("authorization", headers[2].getName());
        assertEquals("Basic Y2xpZW50SWQ6Y2xpZW50U2VjcmV0", headers[2].getValue());

        verify(httpClient).close();
    }

}