11.3 Enterprise JavaBeans Testing Tools

11.3.1 Problem

You want to write tests for Enterprise JavaBeans components.

11.3.2 Solution

Try out ServletTestCase or J2EEUnit.

11.3.3 Discussion

Testing EJB code is challenging because beans only work in the context of an application server. In order to test these beans, your tests must either invoke bean methods through remote interfaces, or be deployed alongside the beans and run on the server.

While you can always write client unit tests that test your EJBs through their remote interfaces, performance may suffer due to the remote calls. The two tools mentioned in this recipe run in a servlet container, typically removing the remote method call overhead. In most cases, particularly in testing environments, the servlet container runs in the same JVM as the EJB container. The shared JVM gives these server-side tests the desired performance boost. ServletTestCase

ServletTestCase is a small application for creating and testing server side code. Your tests extend from junit.framework.ejb.ServerTestCase and you simply add testXXX( ) just as if you were writing a normal JUnit test. The tests are then deployed to your servlet container along with the ServletTestCase application. The tests are executed using Ant's junit task. J2EEUnit

J2EEUnit is a framework for testing server-side code. J2EEUnit uses a servlet as an entry point for executing your EJB tests. Unlike ServletTestCase, you write J2EEUnit tests by extending junit.framework.TestCase. You use the setUp( ) method to retrieve a reference to an EJB. Here's an example:

protected void setUp(  ) throws Exception {
    Context jndiContext = new InitialContext(  );
    Object obj = jndiContext.lookup("java:comp/env/ejb/CustomerBean");
    CustomerHome home = (CustomerHome) 
            PortableRemoteObject.narrow(obj, CustomerHome.class);
    this.customer = home.create(  );

Here's a simple test method:

public void testGetAccountNumber(  ) throws Exception {
    assertEquals("Account Number.", 
                 this.customer.getAccountNumber(  ));

You use org.junitee.anttask.JUnitEETask Ant task to execute the tests.

11.3.4 See Also

ServletTestCase is available at http://www.junit.org/news/extension/j2ee/index.htm. J2EEUnit is available at http://junitee.sourceforge.net.