Overriding methods dynamically
In the previous recipe, Dynamically extending classes with new methods, we learned how to dynamically add a method to a class through one of the metaprogramming features of Groovy, named ExpandoMetaClass
.
In this recipe, we will see how to intercept and replace a call to an existing method of a class. This technique can be very handy when writing unit tests for classes that have dependencies to other classes.
Getting ready
Let's introduce three classes for which we want to write a unit test:
Customer.groovy
:package org.groovy.cookbook class Customer { String name }
CustomerDao.groovy
:package org.groovy.cookbook class CustomerDao { Customer getCustomerById(Long id) { // DO SOME DATABASE RELATED QUERY ... } }
CustomerService.groovy
:package org.groovy.cookbook class CustomerService { CustomerDao dao void setCustomerDao(CustomerDao dao) { this.dao = dao } Customer getCustomer(Long id) { dao.getCustomerById(id) } }
The fictional CustomerService...