![]() | ![]() |
Apache > Jakarta > Cactus > Writing Tests | Docs for: v1.7.2 | v1.7 Last update: March 29 2013 |
When to use?
Your test case class should extend
As filters only exist in Servlet API 2.3, you must use the
Cactus version for Servlet API 2.3 if you wish to write tests for
them.
Filter unit testing is only available in Cactus 1.2 and
above.
Provided Implicit Objects
Cactus automatically initializes the implicit objects for you and
they are made available to your
You may ask yourself how Cactus initializes these objects. The
mechanism is described in the How it
works guide.
The provided implicit objects are: request
See response
See config
Cactus wraps the original Filter Config for two reasons:
The
See the javadoc for the
Additional methodsAdditional methods provided:
filterChain
Cactus does not wrap the filter chain.
Tips and TricksSimulating the next fitler in chainAs you are performing unit testing of your filter, you may wish to simulate the next filter in the filter chain so that you can decide, as part of your unit test, what this other filter returns to your filter under test. Here is how you could do that: public void testDoFilterOK() throws ServletException, IOException { SampleFilter filter = new SampleFilter(); filter.init(config); [...] FilterChain mockFilterChain = new FilterChain() { public void doFilter(ServletRequest theRequest, ServletResponse theResponse) throws IOException, ServletException { PrintWriter writer = theResponse.getWriter(); writer.print("<p>some content</p>"); writer.close(); } public void init(FilterConfig theConfig) { } public void destroy() { } }; filter.doFilter(request, response, mockFilterChain); [...] } See the samples provided as part of the Cactus distribution. Sample
This is a very basic sample intended to give you a flavour of Filter
unit testing. Check the distribution samples for extensive
examples. The filter we are testing here simply adds a header and
a footer to the response. The header and footer texts are
defined as a parameter defined in public void testXXX() throws ServletException, IOException { SampleFilter filter = new SampleFilter(); config.setInitParameter("header", "<h1>header</h1>"); config.setInitParameter("footer", "<h1>footer</h1>"); filter.init(config); FilterChain mockFilterChain = new FilterChain() { public void doFilter(ServletRequest theRequest, ServletResponse theResponse) throws IOException, ServletException { PrintWriter writer = theResponse.getWriter(); writer.print("<p>some content</p>"); writer.close(); } public void init(FilterConfig theConfig) { } public void destroy() { } }; filter.doFilter(request, response, mockFilterChain); } public void endXXX(WebResponse theResponse) { assertEquals("<h1>header</h1><p>some content</p><h1>footer</h1>", theResponse.getText()); } |