Expert Spring MVC and Web Flow

(Dana P.) #1

What If the Code Has Dependencies?


The unit test suggestions, such as testing the smallest amount of code, are quite reasonable
when testing the domain object model, because it is easy to create and control instances of
dependencies. As shown in Listing 10-3, the FlightTestsimply creates new objects such as
FlightLegin order to create certain test conditions. However, if the code requires dependen-
cies that are heavyweight or tied to external resources, writing unit tests becomes more
difficult.
For example, consider how one would write a unit test for the following service layer class.
We’ve created a simple AccountServiceinterface, implemented by AccountServiceImpl, shown
in Listing 10-4. The service class delegates to an AccountDaofor loading Accountinstances from
persistence. The Accountclass implements the business logic for its activation.


Listing 10-4.AccountServiceImpl


public class AccountServiceImpl implements AccountService {


private AccountDao accountDao;

public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}

public void activateAccount(Long accountId) throws AccountNotFoundException {
Assert.notNull(accountId, "accountId must not be null");
Account account = accountDao.getAccount(accountId);
if (account == null) {
throw new AccountNotFoundException(accountId);
}
account.activate();
}

}


We can already see some of the conditions the unit test must test, including:


  • What if the Data Access Object (DAO) returns a nullaccount?

  • What if the method parameter is null?

  • How do we ensure that the account returned by the DAO is the one that is activated?


To successfully test those conditions, the service object requires a functioning DAO. How-
ever, to keep from violating our unit test rules, we must not actually interact with the database.
Therefore, the AccountDaoinstance that the AccountServiceImpluses can’t be the real imple-
mentation. We need to somehow replace the AccountDaowith an object that looks and feels like
the real thing, but instead of pulling objects from the database it returns objects from memory.


CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS 291
Free download pdf