[ Team LiB ] Previous Section Next Section

11.4 Avoiding EJB Testing

11.4.1 Problem

You want to test server-side business logic but avoid the complexity of EJB deployment and remote method calls.

11.4.2 Solution

Decouple business logic from EJBs, facilitating dedicated unit testing without an application server.

11.4.3 Discussion

Example 11-2 shows a code fragment from a stateless session bean. In order to test this bean, you must deploy it to an application server. The deployment steps make your Ant buildfile more complex and slow you down as you write tests, deploy, run your tests, and change your code.

Example 11-2. Part of a stateless session bean
public class AccountBean implements SessionBean {
    // a bunch of EJB methods
    public void ejbCreate(  ) { ... }
    public void ejbActivate(  ) { ... }
    public void ejbPassivate(  ) { ... }
    etc...
   
    public double getBalanceAsOf(Date date) {
        // fetch data
           ...
        // apply interest
           ...
        // deduct bank fees
           ...
    }
}

Fortunately, we can refactor EJBs so they do not require as much testing. If business logic is decoupled from the beans, you can write tests against the business logic without first deploying to an application server. This capability drastically simplifies your tests, while making the whole test-driven development cycle faster.

Example 11-3 shows the improved bean.

Example 11-3. Refactored stateless session bean
public class AccountBean implements SessionBean {
    // a bunch of EJB methods
    public void ejbCreate(  ) { ... }
    public void ejbActivate(  ) { ... }
    public void ejbPassivate(  ) { ... }
    etc...
   
    public double getBalanceAsOf(Date date) {
        // delegate to a businss object
        return AccountBO.getBalanceAsOf(date);
    }
}

The business logic now resides in a dedicated class called AccountBO. In addition to testing benefits, AccountBO is now reusable by other beans and perhaps even by servlets or client code. We don't show AccountBO because it is just an ordinary Java class with a static method. You can test it using JUnit just like any other class.

11.4.4 See Also

This technique was first mentioned in Recipe 6.8.

    [ Team LiB ] Previous Section Next Section