18.7 Mocking Using ExpandoMetaClass
We can intercept method calls in Groovy in another way, using the ExpandoMetaClass (see Section 13.2, Injecting Methods Using ExpandoMetaClass, and Section 13.3, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access