nit testing, a critical part of the software development process, involves individually testing each unit of code to make sure that it works correctly on its own. Performed at different layers of an application, unit tests run best when they are done quickly and kept in mutual isolation.
If the application under test is EJB-driven (that is, if its business logic is encapsulated in EJBs), it makes sense to test the EJB as well. However, unit testing EJBs is a complex job, which becomes even more difficult when the EJBs are secured through method-level, role-based permissions.
A test case typically constructs the object it is testing, but the object being tested is sometimes dependant on the behavior of other objects. In that case, the test case stubs out the needed behavior as a "mocked behavior". This works fine when testing a standalone component, but testing code that runs in an application server, such as EJB, becomes complicated.
EJBs are not supposed to be constructed directly by the callers. They usually require the context provided by the server to properly construct itself. Without that, they don't function correctly. To properly test EJB, you must build the application, deploy the EJB to the application server, and then execute the JUnit tests against the remote interfaces of the EJBs. 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. And again, it becomes more complex when the EJB is secured through method-level permissions, which are related to roles.
Introducing the JUnitEE Unit-Testing Framework
Among the very few unit-testing frameworks that deal with this kind of scenario, Apache Cactus is a prominent one. It extends the JUnit framework to handle unit testing for server-side Java components such as EJBs, servlets, JSPs, etc., and provides an authentication mechanism through its support of the BASIC and FORM authentication methods. This facilitates unit testing of servlet codes that use the Servlet Security API.
A lesser-known unit-testing framework, JUnitEE, is also suitable for running in an application server environment. Although not as versatile as Cactus, JUnitEE is easier to use. It does not provide an authentication mechanism, but you can easily create an API on top of JUnitEE that will handle the authentication process and run test cases in a secured environment.
This article shows how to unit test secured EJBs deployed in the IBM WebSphere Application Server using the JUnitEE framework. Even though it uses IBM WebSphere for demonstration, you can apply its concepts to unit test secured EJBs that are deployed in other application servers as well.