net.paslavsky.springrest.SpringRestClientMethodInterceptorTest.java Source code

Java tutorial

Introduction

Here is the source code for net.paslavsky.springrest.SpringRestClientMethodInterceptorTest.java

Source

/*
 * Copyright (c) 2014 Andrey Paslavsky.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.paslavsky.springrest;

import org.aopalliance.intercept.MethodInvocation;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.client.RestTemplate;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.HashMap;

/**
 * Tests for the {@link SpringRestClientMethodInterceptor}
 *
 * @author Andrey Paslavsky
 * @version 1.0
 */
public class SpringRestClientMethodInterceptorTest {
    private RestTemplate template;
    private SpringRestClientMethodInterceptor interceptor;

    @Spy
    private MockClientHttpRequest request = new MockClientHttpRequest();
    @Mock
    private ClientHttpRequestFactory requestFactory;
    @Mock
    private ClientHttpResponse response;
    @Mock
    private AnnotationPreprocessor annotationPreprocessor;
    @Mock
    private AuthenticationManager authenticationManager;
    @Mock
    private MethodInvocation methodInvocation;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        initRestTemplate();
        createTestedInstance();

        Mockito.when(methodInvocation.getMethod()).thenReturn(ReflectionUtils.findMethod(getClass(), "testInvoke"));
        Mockito.when(methodInvocation.getArguments()).thenReturn(new Object[] { "Request" });
        Mockito.when(annotationPreprocessor.parse(Mockito.any(Class.class), Mockito.any(Method.class)))
                .thenReturn(createNewMetadata());
        Mockito.when(authenticationManager.getAuthenticationHeaders()).thenReturn(getAuthHttpHeaders());
    }

    private HttpHeaders getAuthHttpHeaders() {
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.add("Auth", "######");
        return authHeaders;
    }

    private RestMethodMetadata createNewMetadata() {
        RestMethodMetadata metadata = new RestMethodMetadata();
        metadata.setCommonPath("somePath");
        metadata.setAdditionalPath("/subPath");
        metadata.setHttpMethod(HttpMethod.GET);
        metadata.setResponseClass(String.class);
        metadata.setMethodReturnType(String.class);
        metadata.setUriVarParameters(new HashMap<String, Integer>());
        metadata.setRequestParameter(0);
        metadata.setRequestHeaderParameters(new HashMap<String, Integer>());
        metadata.setQueryParameters(new HashMap<String, Integer>());
        return metadata;
    }

    private void createTestedInstance() {
        interceptor = new SpringRestClientMethodInterceptor(template);
        interceptor.setAnnotationPreprocessor(annotationPreprocessor);
        interceptor.setAuthenticationManager(authenticationManager);
        interceptor.setBaseUrl(URI.create("http://example.com/"));
        interceptor.setConversionService(new DefaultConversionService());
        interceptor.afterPropertiesSet();
    }

    private void initRestTemplate() throws IOException {
        template = new RestTemplate();
        template.setRequestFactory(requestFactory);
        Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
                .thenReturn(request);
        Mockito.when(request.execute()).thenReturn(response);
        Mockito.when(response.getStatusCode()).thenReturn(HttpStatus.OK);
        Mockito.when(response.getRawStatusCode()).thenReturn(HttpStatus.OK.value());
        Mockito.when(response.getStatusText()).thenReturn(HttpStatus.OK.getReasonPhrase());
        Mockito.when(response.getBody()).thenReturn(new ByteArrayInputStream("Test OK!".getBytes()));
        Mockito.when(response.getHeaders()).thenReturn(new HttpHeaders());
    }

    @Test
    public void testInvoke() throws Throwable {
        Assert.assertEquals(interceptor.invoke(methodInvocation), "Test OK!");

        Mockito.verify(methodInvocation, Mockito.times(1)).getMethod();
        Mockito.verify(annotationPreprocessor, Mockito.times(1)).parse(Mockito.eq(getClass()),
                Mockito.eq(ReflectionUtils.findMethod(getClass(), "testInvoke")));
        Mockito.verify(methodInvocation, Mockito.times(1)).getArguments();
        Mockito.verify(authenticationManager, Mockito.times(1)).getAuthenticationHeaders();
        Mockito.verifyNoMoreInteractions(methodInvocation, annotationPreprocessor, authenticationManager);
        Mockito.verify(requestFactory, Mockito.times(1)).createRequest(
                Mockito.eq(URI.create("http://example.com/somePath/subPath")), Mockito.eq(HttpMethod.GET));

        Mockito.verify(request, Mockito.atLeastOnce()).getHeaders();
        Mockito.verify(request, Mockito.atLeastOnce()).getBody();

        Assert.assertEquals(request.getHeaders().getFirst("Auth"), "######");
        Assert.assertEquals(request.getBodyAsString(), "Request");
    }
}