Mocking Using ExpandoMetaClass

We can intercept method calls in Groovy in another way, using the ExpandoMetaClass (see Injecting Methods Using ExpandoMetaClass, and Injecting Methods into Specific Instances). We don’t have to create a separate class as in the two approaches we’ve seen so far. Instead, we can create a closure for each method we want to mock, and set that into MetaClass for the instance being tested. Let’s look at an example.

Create a separate instance of ExpandoMetaClass for the instance being tested. This MetaClass will carry the mock implementation of collaborator methods.

In this example, shown in the following code, we create a closure for mocking println and set that into an instance of ExpandoMetaClass for ClassWithHeavierDependencies ...

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.