bit.changepurse.wdk.http.TestHTTPResponse.java Source code

Java tutorial

Introduction

Here is the source code for bit.changepurse.wdk.http.TestHTTPResponse.java

Source

/*
 * This file is part of ChangePurse.
 *
 * Copyright (c) 2014 Germn Fuentes Capella
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package bit.changepurse.wdk.http;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.junit.Test;

import bit.changepurse.wdk.util.CheckedExceptionMethods;

public class TestHTTPResponse {

    @Test
    public void testStatusCode() {
        CloseableHttpResponse rawResponse = new MockedApacheResponse();
        for (HTTPStatusCode statusCode : HTTPStatusCode.values()) {
            rawResponse.setStatusCode(statusCode.toInt());
            HTTPResponse response = new HTTPResponse(rawResponse);
            assertThat(response.getStatusCode(), equalTo(statusCode));
            assertThat(response.toString(), notNullValue());
        }
    }

    @Test
    public void testGetBody() throws UnsupportedEncodingException {
        HttpEntity entity = new StringEntity("This is a text");
        testGetBody(entity);
    }

    @Test
    public void testLongBody() throws UnsupportedEncodingException {
        HttpEntity entity = new StringEntity(
                "This is a textThis is a textThis is a textThis is a textThis is a textThis is a textThis is a textThis is a text");
        testGetBody(entity);
    }

    @Test
    public void testGetEmptyBody() throws UnsupportedEncodingException {
        testGetBody(null);
    }

    private void testGetBody(HttpEntity entity) throws UnsupportedEncodingException {
        CloseableHttpResponse rawResponse = new MockedApacheResponse();
        rawResponse.setStatusCode(HTTPStatusCode.SUCCESS.toInt());
        rawResponse.setEntity(entity);
        HTTPResponse response = new HTTPResponse(rawResponse);
        assertThat(response.getBody(), equalTo(CheckedExceptionMethods.toString(entity)));
        assertThat(response.toString(), notNullValue());
    }

    @Test
    public void testGetLocation() {
        CloseableHttpResponse rawResponse = new MockedApacheResponse();
        rawResponse.setStatusCode(HTTPStatusCode.SUCCESS.toInt());
        String location = "http://www.google.com";
        rawResponse.addHeader("Location", location);
        HTTPResponse response = new HTTPResponse(rawResponse);
        assertThat(response.getLocationFromHeaders(), equalTo(location));
        assertThat(response.toString(), notNullValue());
    }
}