mockAccountDao.verify();
}
Notice how the initialization of the mockAccountDaoreads very much like the previous
description of the test. You can read the mock object configuration as, “The mockAccountDao
should expect a single call to the getAccount()method with a parameter equal to 1Land will
return the value of null.”
After the configuration, the service method activateAccount()is called with the correct
parameter. When the service method delegates to the accountDao, the mock object will return
nullas instructed. The service object, never the wiser, continues on with its logic and throws
the exception.
If a method was called on the mock that it was not expecting, the mock will cause the test
to fail immediately. However, because there is no immediate failure on expectations never met
(for instance, if a mock method was never called), the verify()method is required to ensure
that the mock will cause a failure if an expectation was never met.
■Tip Always place a call to verify()for every mock you configure in your test case.
Another test we wish to write for the AccountServiceImplobject is the optimistic case
of everything working smoothly. We want to ensure that the Accountobject returned by the
accountDaois correctly activated. For this test, shown in Listing 10-7, instead of returning null
we will return an instance of Accountthat we control. After the service method runs, it will be
easy to check the state of the Accountobject to see whether it was correctly activated.
Listing 10-7.testActivateAccountWithAccount
public void testActivateAccountWithAccount() {
Account account = new Account();
assertFalse(account.isActivated());
mockAccountDao.expects(once())
.method("getAccount")
.with(eq(new Long(1)))
.will(returnValue(account));
accountService.activateAccount(new Long(1));
assertTrue(account.isActivated());
mockAccountDao.verify();
}
The setup for the mock object is very similar to the previous test case. However, for this
test we return a real instance of Account, one that we have created. After the service method
completes, we check that the account was activated.
CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS 295