0

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

Kadoline
  • 7
  • 1
  • 6

2 Answers2

0

It seems userFilterTest is mock. Please mark

@InjectMocks 
private UserFilter userFilterTest;

see the similar question

Dima Ki
  • 16
0

Unfortunate you do not log the the exception.

If you did you would see a ClassCastException occurring at

HttpServletRequest request = (HttpServletRequest) req;

The reason is the your mock has the wrong type:

@Mock
private ServletRequest servletRequest;

instead of

@Mock
private HttpServletRequest servletRequest;

The same is true for the servletResponse.

Conclusion

  • never swallow exceptions!
  • no not use try/catch in unittest

if your test looked like this

@Test

public void testDoFilter() throws Exception{
   Mockito.doReturn(userTest).when(sessionTest).getAttribute(Attribute.ATTRIBUTE_USER);
        userFilterTest.doFilter(servletRequest, servletResponse, filterChain);
        verify(filterChain).doFilter(servletRequest, servletResponse);
}

it would have failed with the ClassCastException.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51