Java Reference
In-Depth Information
Thebusinessmethodsarestraightforward,basedontheaccountscache(themap).Theonly
complicationisdeterminingwhetherornotthecacheneedstoberefreshedbeforereturning
a value. Methods that change the accounts force a write to the file. Methods that retrieve
them just need to check if a read is necessary.
That's a fair amount of code, and I would feel very uncomfortable if it wasn't tested. An
integration test would simply supply an actual file to the DAO, and I have such a test in
the topic's source code. A unit test, however, would remove the dependency on the
File
class. That's where the
Expando
comes in.
The
groovy.util.Expando
class creates an object with no attributes or methods of
its own, other than the ones it inherits. The cool part is that you can treat an instance of
Expando
as though it was a map, where the keys are the names of properties or methods,
and the values are the property values or method implementations.
Expando
A
groovy.util.Expando
is a class that creates an empty object to which you can add
properties and methods as desired.
To see this in action, let me create an
Expando
to act as a replacement for the file in my
DAO. First I have to see what methods in
File
need to be represented.
Here are the methods in
AccountDAO
that use the
accountsFile
dependency. The
methods I need to mock are in bold:
private void readAccountsFromFile() {
accountsFile.
splitEachLine
(',') { line ->
int id = line[0].
toInteger
()
double balance = line[1].
toDouble
()
accounts[id] = new Account(id:id,balance:balance)
}
nextId
= accounts?.keySet().
max
() ?: 0
nextId
++
dirty = false
}