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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access