Your test case class should extend FilterTestCase
whenever you are unit testing:
FilterConfig
, ...)
setUp()
,
testXXX()
and tearDown()
methods as
instance variables of the FilterTestCase
class (and thus
as instance variables of your test case class as it extends
FilterTestCase
).
See ServletTestCase
request
implicit object for documentation.
See ServletTestCase
response
implicit object for documentation.
Instance variable name |
config
|
Class name |
org.apache.cactus.server.FilterConfigWrapper
, which inherits from
javax.servlet.FilterConfig
|
Cactus wraps the original Filter Config for two reasons:
web.xml
, etc...,
config
implicit object will contain all
initialisation parameters defined in web.xml
under the Filter Redirector filter definition.
See the javadoc for the
org.apache.cactus.server.FilterConfigWrapper
class for all details. You should also look at the
samples provided in the Cactus distribution.
Additional methods provided:
setInitParameter()
: sets an initialisation
parameter (as if it has been defined in the web.xml
file),
setFilterName()
: sets the Filter name that will be
returned by getFilterName()
(if not set, the
Cactus Filter redirector name will be returned).
Instance variable name |
filterChain
|
Class name |
javax.servlet.FilterChain
|
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); [...] }
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 web.xml
.
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()); }