3

无论如何要对过滤器进行单元测试,如下所示?

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;
    }
4

1 回答 1

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

在这里我是说当 request.getParmeter 被调用时使用“param”然后返回 null,response.sendError 使用 400 和“param can't be null”参数,应该被调用。

于 2013-03-06T07:41:49.843 回答