Groovy: stub typed reference

Posted by Don on Stack Overflow See other posts from Stack Overflow or by Don
Published on 2009-06-10T18:20:29Z Indexed on 2010/06/17 4:03 UTC
Read the original article Hit count: 272

Filed under:
|

Hi,

I have a Groovy class similar to

class MyClass {

  Foo foo
}

Under certain circumstances I don't want to initialize foo and want to stub out all the calls to it. Any methods that return a value should do nothing. I could do it like this:

Foo.metaClass.method1 = {param -> }
Foo.metaClass.method2 = { -> }
Foo.metaClass.method3 = {param1, param2 -> }

While this will work, it has a couple of problems

  1. Tedious and long-winded, particularly if Foo has a lot of methods
  2. This will stub out calls to any instance of Foo (not just foo)

Although Groovy provides a StubFor class, if I do this:

this.foo = new groovy.mock.interceptor.StubFor(Foo)

I get a ClassCastException at runtime. Although this would work if I could redefine foo as:

def foo

But for reasons I won't go into here, I can't do that.

Thanks, Don

© Stack Overflow or respective owner

Related posts about groovy

Related posts about stubbing