Java Reference
In-Depth Information
{ id -> accounts[id] }
That's a one-argument closure whose dummy variable, again called
id
, returns the
Ac-
count
stored under that ID. With that machinery in place I can provide a stub implement-
ation for the DAO to the service class, as shown in the next listing.
Listing 6.18. A JUnit 4 test case for the
AccountService
, in Groovy, with a stubbed DAO
In the
setUp
method (with the
@Before
annotation), I use the
as
operator to treat the
closure as an
AccountDAO
interface. That means the closure will be used as an imple-
mentation for all the methods in the interface. Because the only method used in the DAO
interface was
findAccountById
, I can assign a single coerced closure to the
dao
prop-
erty in the service (which goes through the
setDao
method, as usual), and I'm done. The
testTransferFunds
method verifies that the initial balances of the two accounts are
as expected, does the transfer, and then checks that the updated balances are correct, keep-
ing in mind that comparing doubles requires a third argument representing the precision.
If I need to implement multiple methods in the interface using a closure, I can supply a
map of closures to method names, where each closure has the proper argument list. For ex-
ample, the following listing shows a map of closures representing the entire
AccountDAO
interface and a few tests showing how it works.