views:

174

answers:

3

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

A: 

You need to pass the Foo instance to your MyClass object. In the test, pass in a stub implementation. In the real program pass in a real implementation.

You don't need any special framework to write the stub. If you're only stubbing queries to Foo and are not interested in expecting commands to it, then it's easier to write a stub implementation by hand. A mock object library is overkill and will confuse later readers of the code who will expect the test to include expectations.

Nat
A: 

I'm guessing this is for test purposes only.

The line

Foo foo

creates a getter / setter pair, so you can inject a mock in your test cases doing:

new MyClass().foo = new MockFoo()

If you don't want to create the mock for yourself, try a mocking library, I recommend using mockito. With this small library you can do something like this:

import static org.mockito.Mockito.*;
new MyClass().foo = mock(Foo.class);
Pablo Fernandez
A: 

I found the solution:

this.foo = {Object[] args -> println "I don't do anything"} as Foo
Don