JBoss.org Community Documentation

8.2.2. The Problem

The situation is common, we have a Bank application that manages Customers which can have one or more BankAccounts. The Bank has different business methods to calculate interest, accept loans, etc. (in production code this would be large and complex methods.) We want to write tests for the Bank's business methods to make sure they work as intended and that we don't introduce bugs if we refactor, extend, modify etc. The Bank has three business methods.

package bank;

import java.util.ArrayList;

import customer.*;

public class BankBusiness {

  private BankAccountDAO bankAccountDAO;

  public BankBusiness() {
    try {
      bankAccountDAO = BankAccountDAOFactory.getBankAccountDAOSerializer();
    }
    catch(Exception e) {
      System.out.println(e.getMessage());
    }
  }

  public boolean creditCheck(Customer c, double amount) {
    return (getSumOfAllAccounts(c) < amount * 0.4);
  }

  public double calculateInterest(BankAccount account) {
    if(account.getBalance() < 1000)
      return 0.01;
    else if(account.getBalance() < 10000)
      return 0.02;
    else if(account.getBalance() < 100000)
      return 0.03;
    else if(account.getBalance() < 1000000)
      return 0.05;
    else
      return 0.06;
  }

  public double getSumOfAllAccounts(Customer c) {
    double sum = 0;
    if(c.getAccounts().size() < 1)
      return sum;
    else {
      for(int i=0; i < c.getAccounts().size(); i++) {
        BankAccount a =
          bankAccountDAO.getBankAccount( ((Long) c.getAccounts().get(i)).longValue());
        if(a != null)
          sum += a.getBalance();
      }
    }
    return sum;
  }

}

calculateInterest(BankAccount b) can easily be tested since it is only dependent on the object it recieves as a parameter.

creditCheck(Customer c, double amount) and getSumOfAllAccounts(Customer) are more complicated since they are data dependent. It uses a DAO layer to fetch all BankAccounts for a specified customer. The test should not be dependent of the DAO implementation since its goal is to check the business logic, not the DAO layer. In this example the DAO implementation is a simple serializer, but it could easily be an Entity beans, Hibernate, etc..