java - 如何使用 Mockito @InjectMocks 将 HttpServletRequest 注入(inject) ContainerRequestFilter

标签 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 实例未注入(inject)并且为 null。

任何人都可以帮我解决我所缺少的东西吗?

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

MockitoAnnotations.initMocks(this);

最佳答案

我可以验证它工作正常。请参阅下面的示例,其中我模拟了 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());
        }
    }
}

关于java - 如何使用 Mockito @InjectMocks 将 HttpServletRequest 注入(inject) ContainerRequestFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51720864/

相关文章:

Java : How to convert java. lang.String 到 ISO 8859-1 格式

python - 应该如何记录单元测试?

javascript - 如何对以 res.send(200, object) 结尾的 javascript 函数进行单元测试

java - 为具有两个 When 语句的测试获取 WrongTYpeOfReturnValue

java - Mockito - 如何避免将数据插入数据库?

java - Eclipse IDE,Blue Scope WTF

java - HttpServletRequest.getRequestURL() 是否可欺骗?

java - 如何打印已转换为对象的数组?

c# - 如何对调用 Action 的 HTML Helper 进行单元测试?

java - 使用 Mockito 来模拟某些方法,但不能模拟其他方法