无论如何要对过滤器进行单元测试吗?
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String param = request.getParameter("param");
if (param == null) {
response.sendError(400, "param can't be null");
return;
}
答案 0 :(得分:4)
是的,有,这是一种方式。在这里,我模拟HttpServletRequest和HttpServletResponse,并通过定义期望来断言方法调用。这里我使用的是JMock。
public class SampleFilterTest {
private Mockery context = new Mockery();
private SampleFilter sampleFilter = new SampleFilter();
private HttpServletRequest request;
private HttpServletResponse response;
@BeforeMethod
public void setUp() throws Exception {
request = context.mock(HttpServletRequest.class);
response = context.mock(HttpServletResponse.class);
}
@Test
public void sampleFilterTest() throws IOException, ServletException {
context.checking(new Expectations() {{
oneOf(request).getParameter("param");
will(returnValue(null));
oneOf(response).sendError(400, "param can't be null");
}});
sampleFilter.doFilter(request, response, null);
}
}
这里我说当使用“param”调用request.getParmeter然后返回null,并且应该调用带有400的response.sendError和“param不能为null”参数。