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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.junit.Test;

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

public class BaseServiceTest {

    private final BaseService baseService = new BaseService("https://example.com");

    @Test
    public void parseValidJsonTest() throws Exception {
        AuthToken token = baseService.parse("{\"access_token\":\"abc\"}", AuthToken.class);
        assertEquals("abc", token.getAccessToken());
    }

    @Test
    public void parseInvalidJsonChainsCauseTest() {
        try {
            baseService.parse("not valid json", AuthToken.class);
            fail("Expected an exception for invalid JSON");
        } catch (Exception e) {
            assertEquals("Unable to parse response", e.getMessage());
            assertTrue(e.getCause() instanceof com.fasterxml.jackson.core.JsonProcessingException);
        }
    }

    @Test
    public void getResultReadsResponseBodyTest() throws Exception {
        HttpResponse response = mock(HttpResponse.class);
        HttpEntity entity = mock(HttpEntity.class);
        when(response.getEntity()).thenReturn(entity);
        when(entity.getContent()).thenReturn(
                new ByteArrayInputStream("{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8)));

        String result = BaseService.getResult(response);

        assertEquals("{\"foo\":\"bar\"}", result);
    }

}