Kadoline Kadoline - 9 months ago 38
Java Question

How to test a filter in a java application using mockito

I have filter:

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;
} else {
chain.doFilter(req, resp);

And I have my test:

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

public void setUp() {

public void testDoFilter() {
try {
userFilterTest.doFilter(servletRequest, servletResponse, filterChain);
verify(filterChain).doFilter(servletRequest, servletResponse);
} catch (IOException | ServletException e) {

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

private UserFilter userFilterTest;

see the similar question

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