[ Team LiB ] |
7.10 Testing Servlet Initialization Parameters7.10.1 ProblemYou want to set up your servlet tests to execute with different initialization parameters without modifying the deployment descriptor (web.xml) file. 7.10.2 SolutionUse the implicit config object, declared by the ServletTestCase redirector, to set up initialization parameters before invoking methods on a servlet. 7.10.3 DiscussionEach registered servlet in a web application can be assigned any number of specific initialization parameters using the deployment descriptor. Initialization parameters are available to the servlet by accessing its ServletConfig object. The ServletConfig object is created by the server and given to a servlet through its init(ServletConfig) method. The servlet container guarantees that the init( ) method successfully completes before allowing the servlet to handle any requests. Creating a Cactus test for testing initialization parameters is tricky because we have to play the role of the servlet container. Specifically, we have to make sure to call the servlet's init(ServletConfig) method, passing the implicit config object. Failure to call init(ServletConfig) results in a NullPointerException when invoking methods on the servlet's ServletConfig object.
Here is an example test method that shows how to correctly set up the servlet: public void testValidInitParameters( ) throws Exception { this.config.setInitParameter(ConfigParamServlet.CONFIG_PARAM, ConfigParamServlet.CONFIG_VALUE); // critical step! this.servlet.init(this.config); assertTrue("Valid Init Parameter.", this.servlet.validateInitParameters( )); } The ServletTestCase redirector servlet provides an implicit object named config. This object is of type org.apache.cactus.server.ServletConfigWrapper and provides methods to set initialization parameters. Thus, you can add initialization parameters without having to modify the deployment descriptor, the web.xml file. This technique provides a flexible alternative to writing and managing different deployment descriptors for testing purposes. Now your tests can set up valid and invalid initialization parameters for each test method and verify that the servlet handles them appropriately. 7.10.4 See AlsoSee Recipe 7.7 for a discussion on alternate ways to test servlet code that may or may not depend on the behavior of an actual running server. |
[ Team LiB ] |