7.15 When Not to Use Cactus

7.15.1 Problem

You want to test a utility class that your servlet uses.

7.15.2 Solution

Design most of your application logic to be independent of servlets and JSPs and then use JUnit to test standalone, non-server code.

7.15.3 Discussion

Cactus is a good testing framework, but testing server-side code is still a significant challenge. For this reason, you should strive to minimize the amount of code that can only be tested when running in an application server. Putting too much application logic directly into servlets and JSPs is a common mistake. Whenever possible, you should strive to write standalone helper classes that your servlets and JSPs delegate to. Provided that these classes do not have dependencies on interfaces like HttpServletRequest, HttpServletResponse, or HttpSession, they are much easier to test using JUnit.

A perfect example is Recipe 7.9, on testing session-tracking code. The ShoppingCart and Item objects are not dependent on a running server, and therefore should be tested using JUnit.

7.15.4 See Also

For more information on testing non-server specific code, see Chapter 4. Recipe 7.9 shows how to test the use of an HttpSession for handling user sessions. Recipe 7.16 discusses designing JSPs to use standalone helper classes.