Mocking Using Expando

So far in this chapter we’ve looked at ways to mock instance methods called from within another instance method. In the rest of this chapter, we’ll look at ways to mock other objects on which our code depends.

Let’s take a look at an example. Suppose the methods of a class we’re interested in testing depend on a File. That’ll make it hard to write a unit test. We need to find ways to mock this object so our unit tests on our class can be quick and automated:

UnitTestingWithGroovy/com/agiledeveloper/ClassWithDependency.groovy
 
package​ com.agiledeveloper
 
 
public​ ​class​ ClassWithDependency
 
{
 
def​ methodA(val, file)
 
{
 
file.write ​"The value is ​${val}​."
 
}
 
def​ methodB(val)
 
{
 
def​ file = ​new​ java.io.FileWriter(​ ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.