package io.ljunggren.usps.api.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.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 org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.jupiter.api.Test;
import io.ljunggren.usps.api.model.address.Address;
public class ZipCodeServiceTest {
private final ZipCodeService zipCodeService = new ZipCodeService("https://example.com");
@Test
void lookupReturnsParsedAddress() throws Exception {
CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
CloseableHttpResponse response = HttpTestUtils.mockResponse(200,
"{\"city\":\"Anytown\",\"state\":\"CA\"}");
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
Address address = zipCodeService.lookup("90210", "token", httpClient);
assertNotNull(address);
assertEquals("Anytown", address.getCity());
verify(httpClient).close();
}
@Test
void lookupThrowsOnThrottling() throws Exception {
CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
CloseableHttpResponse response = HttpTestUtils.mockResponse(429, "");
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
assertThrows(Exception.class, () -> zipCodeService.lookup("90210", "token", httpClient));
verify(httpClient).close();
}
@Test
void lookupThrowsOnNotFound() throws Exception {
CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
CloseableHttpResponse response = HttpTestUtils.mockResponse(404, "{\"error\":\"not found\"}");
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
Exception ex = assertThrows(Exception.class, () -> zipCodeService.lookup("90210", "token", httpClient));
assertEquals(true, ex.getMessage().contains("404"));
}
}