2011/08/05 - Jakarta Cactus has been retired.

For more information, please explore the Attic.


This document explains how to unit test EJBs with Cactus. It is divided in 2 parts:

EJB unit testing works with Cactus 1.0 or later. EJB3 unit testing works with Cactus 1.8.1 or later.

General Concepts

Why use Cactus for testing EJBs?

You might be wondering why you would use Cactus to unit test your EJBs whereas you could use standard JUnit test cases. Indeed, you could write a standard JUnit test case and view your code as client side code for the EJB to test ... There are actually a few reasons to choose Cactus instead:
  • If you are using local interfaces (EJB 2.0), then your beans cannot be called remotely (i.e. the caller need to be in the same jvm). However, as all Cactus redirectors run on the server side, you can unit test your local interfaces with Cactus.
  • Very often the production code that will call the EJBs is server side code (Servlets, JSPs, Tag libs or Filters). This means that if you run the tests from a standard JUnit test case, your tests will run in a different execution environment than the production one, which can lead to different test results,
  • An application using EJBs very often includes a front end part which is in almost all cases a web application (i.e. using Servlets, JSP, Tag libs or Filters). It means that you would also need a framework for unit testing these components. Cactus is providing a comprehensive and consistent framework for testing all server side components. This is a compelling enough reason to use it !
  • Cactus provides automated Ant tasks to automatically start your EJB server, run the tests and stop it, thus automating your entire test process and making it easy to implement continuous build and continuous integration of your J2EE project.

The process

You can unit test your EJBs from any of Cactus redirectors: ServletTestCase, JspTestCase or FilterTestCase. This means that you would write a test case class that extends any of Cactus redirectors, get a home reference to your EJB, create an instance of it, call the method to test and perform asserts on the result. It is that simple ! What is slightly more complex is the deployment of your EJBs to your EJB container but you should be familiar with this, right?

J2EE RI Tutorial

This J2EE RI tutorial is a step by step guide for writing Cactus EJB unit test for the Sun J2EE RI server.