如何使用mockito在java应用程序中测试过滤器

时间:2017-08-16 18:53:10

标签: java web filter mockito

我有过滤器:

@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);

我有我的考试:

@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();
    }
}

我不知道我的测试有什么问题。写入从未调用verify()中的方法。请帮忙

2 个答案:

答案 0 :(得分:0)

似乎userFilterTest是模拟的。请标记

@InjectMocks 
private UserFilter userFilterTest;

查看类似的question

答案 1 :(得分:0)

不幸的是,你没有记录例外。

如果你这样做,你会在

看到ClassCastException
HttpServletRequest request = (HttpServletRequest) req;

原因是你的mock有错误的类型:

@Mock
private ServletRequest servletRequest;

而不是

@Mock
private HttpServletRequest servletRequest;

servletResponse也是如此。

结论

  • 从不吞下异常!
  • 请勿在unittest中使用try / catch

如果您的测试看起来像这样

@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);
}

它会因ClassCastException而失败。