Java Reference
In-Depth Information
counts. Therefore, in order to do its job the AccountService needs an AccountDAO
instance.
The AccountService is tied to the AccountDAO . A true unit test would test this class
in isolation, meaning I need to provide some kind of stub for the AccountDAO class. Ac-
countDAO is actually an interface, as shown in the next listing.
Listing 6.17. The AccountDAO interface, with CRUD methods for the Account class
public interface AccountDAO {
Account findAccountById(int id);
Collection<Account> findAllAccounts();
int createNewAccount(double balance);
void deleteAccount(int id);
}
If I create a stub implementation of the AccountDAO interface, I need to implement all
these methods. Notice, however, that the AccountService only uses one method out
of the interface: findAccountById . That's the only method I actually need. Unfortu-
nately, I can't implement only that method. When implementing an interface I need to im-
plement all its methods, whether I plan to use them or not.
I can use a Groovy technique to avoid all the extra work. If I provide a closure with the
same argument list as the method I care about, I can then “coerce” the closure into the in-
terface. The closure becomes the implementation of all the methods in the interface with
the same argument list.
In this case I want to provide an implementation for the findAccountById method,
which takes an integer id and returns an Account . I'm going to use a map to accomplish
this:
Account a1 = new Account(1,100)
Account a2 = new Account(2,100)
def accounts = [1:a1, 2:a2]
The Account class (not shown, but it's a simple POJO contained in the topic source code)
hasatwo-argument constructor that takes an id andaninitial balance .Iinstantiated two
accounts with IDs 1 and 2 and added them to a map under the ID values. Now I need the
closure that implements my method:
Search WWH ::




Custom Search