如何使用Mockito @InjectMocks将HttpServletRequest注入ContainerRequestFilter

时间:2018-08-07 07:10:23

标签: java unit-testing mockito jax-rs

我无法在此处复制确切的代码,但是我将放置一个示例类来解释我所面临的问题。

public XYZ implements ContainerRequestFilter{

    @Context
    HttpServletRequest httpServletRequest;

    @Override
    public void filter(ContainerRequestContext abc){
        //rest of the code below where httpServletRequest is used inside 
    }
}

因此,当我使用@InjectMocks编写写测试代码时,HttpServletRequest实例不会被注入并且为空。

任何人都可以在这里帮助我我所缺少的东西。

我什至在@Before方法中使用了以下内容,但仍然没有解决方法。

MockitoAnnotations.initMocks(this);

1 个答案:

答案 0 :(得分:1)

我可以确认它运行正常。请参见下面的示例,其中在模拟HttpServletRequest并在调用getRemoteAddr()时提供一个远程地址。我使用该模拟值在ContainerRequestContext中设置属性。然后,我使用ArgumentCaptor来捕获要测试的值。

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import static org.assertj.core.api.Assertions.assertThat;

public class MockitoInjectMocksTest {

    @Mock
    private HttpServletRequest request;

    @Mock
    private ContainerRequestContext requestContext;

    /**
     * With the @InjectMocks annotation, Mockito will
     * inject the filter with the mock HttpServletRequest
     */
    @InjectMocks
    private Filter filter = new Filter();

    @Before
    public void setUp() {
        // Handle all the mock creation and injection.
        MockitoAnnotations.initMocks(this);

        // Mock the HttpServletRequest#getRemoteAddr()
        // method to return a dummy IP address.
        Mockito.when(request.getRemoteAddr())
                .thenReturn("122.21.32.233");
    }

    /**
     * See the `Filter` class below. The `filter()` method doesn't
     * do much. It just grabs the remote IP address from the
     * `HttpServletRequest` and uses it to set a property on
     * the `ContainerRequestContext`. This test asserts that
     * the arguments passed to the `setProperty()` method
     * method are the correct arguments. We do that with the
     * help of Mockito's `ArgumentCaptor`,
     */
    @Test
    public void testIpPropertySet() throws Exception {
        // Call the `filter()` method that we are testing,
        // passing in the mock `ContainerRequestContext`.
        // We use a mock so that we can later verify methods
        // on it are called
        filter.filter(requestContext);

        // We create argument captors to capture the args of call to
        // `ContainerRequestContext#setProperty(String, String)`
        ArgumentCaptor<String> propNameArg = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<String> propValArg = ArgumentCaptor.forClass(String.class);

        // Verify the `ContainerRequestContext#setProperty()`
        // is called. We use the `ArgumentCaptors` to capture
        // the arguments that are passed when `setProperty()`
        // is called.
        Mockito.verify(requestContext)
               .setProperty(propNameArg.capture(), propValArg.capture());

        // Test that the arguments passed in the call to
        // `ContainerRequestContext#setProperty()` are correct.
        assertThat(propNameArg.getValue()).isEqualTo("RemoteAddress");
        assertThat(propValArg.getValue()).isEqualTo("122.21.32.233");
    }

    public static class Filter implements ContainerRequestFilter {

        @Context
        private HttpServletRequest request;

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            System.out.println(request.getRemoteAddr());
            requestContext.setProperty("RemoteAddress", request.getRemoteAddr());
        }
    }
}