Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 10-5. AccountServiceImplTest Setup

public class AccountServiceImplTest extends MockObjectTestCase {

private AccountService accountService;
private Mock mockAccountDao;
private AccountDao accountDao;

protected void setUp() throws Exception {
super.setUp();
accountService = new AccountServiceImpl();
mockAccountDao = mock(AccountDao.class);
accountDao = (AccountDao) mockAccountDao.proxy();
((AccountServiceImpl)accountService).setAccountDao(accountDao);
}

Notice how we require two distinct objects for the mock: an instance of mock and its
proxy. The mock is the object the test configures and controls, while the proxy is the stand-in
we provide to the service object.
The setup()method introduces the mock() method, the first helper method provided by
the MockObjectTestCaseclass. This method is a builder, accepting an interface and returning
an instance of its mock.

■Tip Programming with interfaces allows you to easily work with mock object libraries.


With the mock created, let’s now create the first unit test for this class (Listing 10-6). We
will test that the service object will throw an AccountNotFoundExceptionif the DAO returns a
null Account. This will require the mock to be instructed to expect a single call to getAccount()
with a parameter equal to what we provide to the service object, and to return a value of null.

Listing 10-6.testActivateAccountWithNoAccountFound

public void testActivateAccountWithNoAccountFound() {
mockAccountDao.expects(once())
.method("getAccount")
.with(eq(new Long(1)))
.will(returnValue(null));

try {
accountService.activateAccount(new Long(1));
fail("Should have thrown AccountNotFoundException");
} catch(AccountNotFoundException e) {
assertTrue(e.getMessage().contains("1"));
}

294 CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS

Free download pdf