简体   繁体   English

模拟 WebApplicationContext 以在过滤器 junit 测试中获取属性

[英]Mock WebApplicationContext to get property in Filter junit test

I have a filter where I use some property from servlet context in its init method:我有一个过滤器,我在它的 init 方法中使用来自 servlet 上下文的一些属性:

    @Override
public void init(FilterConfig filterConfig) {
    prop = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getEnvironment().getProperty("my.property");

}

I am writing the unit test for this filter but I can't figure out how to mock WebApplicationContext to use WebApplicationContextUtils and set this property.我正在为此过滤器编写单元测试,但我不知道如何模拟 WebApplicationContext 以使用 WebApplicationContextUtils 并设置此属性。 Here's what I've tried so far:这是我到目前为止所尝试的:

class FilterTest {
    @MockBean
    private FilterChain chain;
    @MockBean
    private WebApplicationContext webAppContextMock;
    @MockBean
    private HttpServletRequest httpServletRequest;
    @MockBean
    private HttpServletResponse httpServletResponse;
    @Autowired
    private MyFilter myFilter;
 @Test
    void doFilter() throws IOException, ServletException {
        MockServletContext mockServletContext = new MockServletContext();
        mockServletContext.setAttribute("my.property", "Property");
        Mockito.when(WebApplicationContextUtils.getWebApplicationContext(Mockito.any(ServletContext.class))).thenReturn(webAppContextMock);

}

I am having a npe due to webApplicationContext, and I should map this servlet context to webApplicationContext.由于webApplicationContext,我有一个npe,我应该map这个servlet上下文到webApplicationContext。 What I am missing here?我在这里缺少什么? Thanks in advance!提前致谢!

Here the problem is getRequiredWebApplicationContext() is a static method of class WebApplicationContextUtils and it cannot be mocked directly using JUnit.这里的问题是getRequiredWebApplicationContext()是 class WebApplicationContextUtils 的 static 方法,不能直接使用 JUnit 模拟。 If you really want to mock it then use power mock.如果您真的想模拟它,请使用 power mock。 https://github.com/powermock/powermock/wiki/Mockito https://github.com/powermock/powermock/wiki/Mockito

I followed another approach for the sake of simplicity, in my filter I just removed the init part and injected Environment bean like this:为了简单起见,我采用了另一种方法,在我的过滤器中,我只是删除了 init 部分并注入了 Environment bean,如下所示:

    private final Environment environment;

public MyFilter(Environment environment) {
    this.environment = environment;
}

in doFilter method:在 doFilter 方法中:

String prop = environment.getProperty("my.property");

and then in my test, the filter was able to access my.property since Environment had access to it.然后在我的测试中,过滤器能够访问 my.property 因为 Environment 可以访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM