Kadoline Kadoline - 9 months ago 38
Java Question

How to test a filter in a java application using mockito

I have filter:

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
User user = (User) request.getSession().getAttribute(Attribute.ATTRIBUTE_USER);
if (user == null) {
HttpServletResponse response = (HttpServletResponse) resp;
response.sendRedirect("/controller?command=goToError");
} else {
chain.doFilter(req, resp);


And I have my test:

@Mock
private FilterChain filterChain;
@Mock
private HttpSession sessionTest;
@Mock
private User userTest;
@Mock
private UserFilter userFilterTest;
@Mock
private ServletResponse servletResponse;
@Mock
private ServletRequest servletRequest;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}

@Test
public void testDoFilter() {
Mockito.doReturn(userTest).when(sessionTest).getAttribute(Attribute.ATTRIBUTE_USER);
try {
userFilterTest.doFilter(servletRequest, servletResponse, filterChain);
verify(filterChain).doFilter(servletRequest, servletResponse);
} catch (IOException | ServletException e) {
fail();
}
}


I dont know what is the problem with my test. Writes that the method which in verify() has never been called. Please help

Answer Source

It seems userFilterTest is mock. Please mark

@InjectMocks 
private UserFilter userFilterTest;

see the similar question

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download