1

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!

YanetP1988
  • 1,346
  • 3
  • 18
  • 43

2 Answers2

0

Here the problem is getRequiredWebApplicationContext() is a static method of class WebApplicationContextUtils and it cannot be mocked directly using JUnit. If you really want to mock it then use power mock. https://github.com/powermock/powermock/wiki/Mockito

  • I was thinking about an alternative way and not having to add a new dependency like PowerMock – YanetP1988 Mar 30 '21 at 17:36
  • If you don't want to use power mock then you can do something like this mentioned here https://stackoverflow.com/questions/44967108/how-to-mock-static-method-without-powermock – Sarthak Sharma Mar 30 '21 at 17:45
0

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.

YanetP1988
  • 1,346
  • 3
  • 18
  • 43