views:

46

answers:

1

I am currently trying to go back through and write unit tests for some code that wraps an existing class. The function I am looking for has code that looks like the following...

private OldObject oldObject
...
public Boolean method(){
  Boolean returnValue = false
  if(oldObject.method(100)){
    returnValue = true  
  }
  if(oldObject.method(101)){
    returnValue = true
  }
}

I have thought about using metaClass, something like OldObject.metaClass.method{return true} but I'm not sure how to remove this before the next tests.

Anyone have best practices/help for this kind of situation?

A: 

To mock the method use:

OldObject.metaClass.method = {return true}

Be aware that this will mock the method for all instances of OldObject, but it's also possible to mock the method just for a single instance. When you want to remove the mocked method just set the metaClass to null:

OldObject.metaClass = null

I think you need to be using at least Groovy 1.6 for this to work.

Don