我有过滤器:
@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()中的方法。请帮忙
答案 0 :(得分:0)
答案 1 :(得分:0)
不幸的是,你没有记录例外。
如果你这样做,你会在
看到ClassCastException
HttpServletRequest request = (HttpServletRequest) req;
原因是你的mock有错误的类型:
@Mock private ServletRequest servletRequest;
而不是
@Mock
private HttpServletRequest servletRequest;
servletResponse
也是如此。
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
而失败。