Java Reference
In-Depth Information
}
}
In a way, I got lucky with this example. The variable I needed to stub, accountsFile ,
was exposed as a property, so I could assign the Expando to it from outside. What if that's
not the case? What if the variable is instantiated inside the class? Can anything be done
then?
If I'm limited to Java, I'm out of luck. [ 11 ] In fact, even mocking frameworks have trouble
with this situation. Fortunately, Groovy has a built-in mechanism for handling exactly this
problem. The classes I need are called StubFor and MockFor .
11 Unless I have AspectJ available, but even then the solution is complicated.
6.3.3. StubFor and MockFor
A typical Groovy developer doesn't necessarily spend a lot of time metaprogramming, but
they sure reap the benefits of it. I use builders in several places in this topic. Domain-spe-
cific languages (DSLs) like GORM, are built through metaprogramming techniques. The
whole Groovy JDK is created through metaclass manipulation. In the last section I used an
Expando to create a test object, and that only works in a language that supports metapro-
gramming. After a while you get used to metaprogramming capabilities and aren't really
surprised by their benefits any more.
In this section I'm going to show a technique that, even after all my years of programming
in Groovy, still feels like magic. I know it works, and I use it wherever I can, but every
time it happens I have to take a moment to sit back and smile at how cool it is.
Let megodirectly totheexample Iwanttoshowandthenexplain thestubtechnique. Rath-
er than use the bank account system described so far, let me remind you of the geocoder
example I've used in several chapters of this topic. The next listing shows the Geocoder
class that's part of the Groovy Baseball system described in chapter 2 .
 
Search WWH ::




Custom Search