7.10 Testing Servlet Initialization Parameters

7.10.1 Problem

You want to set up your servlet tests to execute with different initialization parameters without modifying the deployment descriptor (web.xml) file.

7.10.2 Solution

Use the implicit config object, declared by the ServletTestCase redirector, to set up initialization parameters before invoking methods on a servlet.

7.10.3 Discussion

Each 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.

Is Cactus Overkill, Again?

Before writing any test, especially a server-side test, determine if the behavior of the server is needed for the test to pass. In this recipe, do we need the behavior of the servlet container to test initialization parameters? The answer is not black and white. If you are testing that valid and invalid initialization parameters are properly handled by your servlet, you may not need the behavior of a servlet container. You can get away with using JUnit. On the other hand, if you are testing that an initialization parameter causes the servlet to invoke or retrieve an external resource, a Cactus test may be what you want.

Here is an example test method that shows how to correctly set up the servlet:

public void testValidInitParameters(  ) throws Exception {

    // critical step!
    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 Also

See 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.