2013-03-05 265 views
1

是否有單元測試過濾器如下?如何Junit測試servlet-filters

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

看看這一個:http://stackoverflow.com/questions/11451917/how-do-i-unit-test-a-serlvet-filter-with-junit – 2013-03-05 16:07:20

回答

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被稱爲與「參數」,然後返回null,並response.sendError,400,和「參數不能爲空」參數,應該叫。