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!