Testing Java Enterprise Applications with Cactus
- Issues with JUnit testing of EJBs
- Example Code
- Developing Local Tests
- The Ant Task
- Conclusion
Cactus extends the functionality of JUnit and allows for the automatic testing of server-side components. Although this testing is normally limited to tag libraries and servlets, it is also possible to test local and remote interfaces to Enterprise Java Beans that use Cactus. Cactus is an open source project produced by the Apache Foundation and is part of the Jakarta Project. You can download Cactus here.
As discussed in my previous Cactus article, "An Introduction to Cactus," Cactus works very similar to JUnit and is in fact built upon JUnit. However, instead of each test being comprised of a single method, there are three methods for each test:
- beginXXX—This method is executed from the "client" jvm and is intended to prepare a web request. A request object that will be used in the server-side call is passed into this method.
- testXXX—This method is executed from the "server" jvm and runs in the same space as the servlets or server-side processes. This method is intended to execute methods on the servlet to test them.
- endXXX—This method is executed from the "client" jvm and is intended to confirm results from the server-side processing.
These methods and this configuration can be utilized to test more than just tag libraries and servlets.
Issues with JUnit testing of EJBs
JUnit itself is an incredible tool for initial testing of Java code as well as regression testing of your code. Once you get into the habit of writing test cases for all your classes, productivity increases, and the quality of the code improves. When you have JUnit tests for all your classes, you can refactor your code and ensure that functionality is maintained.
An issue comes up when testing Enterprise Java Beans. To properly test them, you need to build the application, deploy it to the application server, and then execute the JUnit tests against the remote interfaces of the beans. This removes a lot of the automation from the testing, and (as we all know) the harder it is to test, the less testing will get done.
Cactus helps to resolve this issue. Because Cactus starts up the application server internally, there is no need to build and deploy the application prior to testing. By utilizing the client and server JVMs, it is possible to test both the local and remote interfaces for all the beans without having to do anything more than execute the ant task.