Testing Servlet Initialization Parameters

Problem

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

Solution

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

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.

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.