[ Team LiB ] |
11.4 Avoiding EJB Testing11.4.1 ProblemYou want to test server-side business logic but avoid the complexity of EJB deployment and remote method calls. 11.4.2 SolutionDecouple business logic from EJBs, facilitating dedicated unit testing without an application server. 11.4.3 DiscussionExample 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 beanpublic 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 beanpublic 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 AlsoThis technique was first mentioned in Recipe 6.8. |
[ Team LiB ] |