Java Mailing List Archive

http://www.gg3721.com/

Home » user.groovy »

[groovy-user] Mocking Classes using Closures?

simonz

2008-08-23

Replies: Find Java Web Hosting

Author LoginPost Reply

Hello all,

I've started using Groovy a lot for testing and it works wonderfully when
objects are defined by interfaces because I can mock them with a Map, but
I'm frequently bumping into the problem of what to do when a class has
collaborators that are other classes, not interfaces. Eg:

---- Java:

class Bar {
 public void bar() {
   ...
 }
}

class Foo {
 public Bar bar;
 public void foo() {
   bar.bar();
 }
}

Now I want to write a test to ensure bar() method is called when Foo.foo()
is invoked. If Bar was an interface it would be no problem:

---- Groovy:

def called = false;
def bar = [ bar: { called = true; }] as Bar // Nice!
new Foo(bar: bar).foo();
assert called;

But how do I do that now that Bar is a class?  Assume that the classes
under test are legacy Java code and I can't rewrite them to be more "groovy"
(although I would like to!).  Assume also that they have a lot more methods
and state than in this example, the above code is just to demonstrate the
point.

Just wondering if there is a nice solution that I am missing here!

Cheers & thanks!

Simon.
--
Sent from the groovy - user mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

  http://xircles.codehaus.org/manage_email


©2008 gg3721.com - Jax Systems, LLC, U.S.A.