Sunday, April 22, 2012

How to do JUnit testing with servlet filters


JDK and eclipse compatibility

JDK version 1.6 with eclipse 3.3 is the minimum requirement.

Preamble

Download using the download link. Import the eclipse project and run configuration for PublicCryptoKeyFilterTest.

Overview of project

The web project contain sample servlet filters for mock purpose. The sample implementation calls the filter with in the filter to simulate the testing environment.

This project uses the power of mock objects provided by Spring Mock , JUnit4 and some nice tweaking to leverage the mock classes to test filters.

Run the PublicCryptoKeyFilterTest configuration to see the test cases passing by calling the filters for testing.

Unit test case 
@Test
 public void testCryptoKeyFilter() throws Exception {

  PublicCryptoKeyFilter filter = new PublicCryptoKeyFilter();

  final MockRequestDispatcher requestDispatcher = new MockRequestDispatcher(
    "");

  // http servlet mocked for mocked dispatcher
  MockHttpServletRequest request = new MockHttpServletRequest() {

   @Override
   public RequestDispatcher getRequestDispatcher(String mappingURI) {
    setAttribute("mappingURI", mappingURI);
    return requestDispatcher;
   }
  };

  MockHttpServletResponse response = new MockHttpServletResponse();
  MockFilterConfig config = new MockFilterConfig();
  final PrivateCryptoKeyFilter dsFilter = new PrivateCryptoKeyFilter();

  FilterChain filterChain = new MockFilterChain() {
   @Override
   public void doFilter(ServletRequest req, ServletResponse res) {
    try {
     dsFilter.doFilter(req, res, new MockFilterChain());
    } catch (Exception e) {
    }
   }
  };

  request.setRequestURI("http://localhost:8080");

  request.addHeader("Param1", "no-header");

  config.addInitParameter("init-params", "config.props");
  filter.init(config);
  filter.doFilter(request, response, filterChain);
  Assert.assertTrue((request.getAttribute("mappingURI").toString()
    .equalsIgnoreCase("/jsp/error.jsp")));
 }
 
Enjoy, if you like it please appreciate!