Java Reference
In-Depth Information
Listing 7.2 AccountService.java
[...]
public class AccountService {
private AccountManager accountManager;
public void setAccountManager(AccountManager manager) {
this .accountManager = manager;
}
public void transfer(String senderId, String beneficiaryId, long amount) {
Account sender = this .accountManager.findAccountForUser(senderId);
Account beneficiary =
this .accountManager.findAccountForUser(beneficiaryId);
sender.debit(amount);
beneficiary.credit(amount);
this .accountManager.updateAccount(sender);
this .accountManager.updateAccount(beneficiary);
}
}
We want to be able to unit test the AccountService.transfer behavior. For that pur-
pose, we use a mock implementation of the AccountManager interface (listing 7.3).
We do this because the transfer method is using this interface, and we need to test it
in isolation.
Listing 7.3 MockAccountManager.java
[...]
import java.util.HashMap;
public class MockAccountManager implements AccountManager {
private Map<String, Account> accounts = new HashMap<String, Account>();
public void addAccount(String userId, Account account) {
this .accounts.put(userId, account);
}
B
public Account findAccountForUser(String userId) {
return this .accounts.get(userId);
}
C
public void updateAccount(Account account) {
// do nothing
}
}
The addAccount method uses an instance variable to hold the values to return B .
Because we have several account objects that we want to be able to return, we store the
Account objects to return in a HashMap . This makes the mock generic and able to sup-
port different test cases: one test could set up the mock with one account, another test
could set it up with two accounts or more, and so forth.
In C we implement a method to retrieve the account from the accounts map—
we can retrieve only accounts that have been added before that. The updateAccount
D
 
 
 
 
Search WWH ::




Custom Search