Search code examples
javaspring-bootjunitmockitoservlet-filters

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:

    @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. 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. What I am missing here? Thanks in advance!


Solution

  • I followed another approach for the sake of simplicity, in my filter I just removed the init part and injected Environment bean like this:

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

    in doFilter method:

    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.