Home > Groovy, TDD > Mocking and stubbing in Groovy with ‘with’

Mocking and stubbing in Groovy with ‘with’

I often use metaClass in Groovy to create mocks or stubs in my unit tests. Recently I’ve discovered that the with method makes this a bit simpler.

This:

Foo.metaClass.with {
  doSomething = {
    return true
  }
  anotherThing = {foo ->
    assertEquals 42, foo
  }
}

is slightly shorter than this:

Foo.metaClass.doSomething = {
  return true
}
Foo.metaClass.anotherThing = {foo ->
  assertEquals 42, foo
}

and less code means less bugs.

[Update: For more explanation of why the with method is so great, read this post.]
[Update: And for another way to write your mocks and stubs, see my previous post on mocking with Groovy.]

Advertisements
  1. No comments yet.
  1. December 31, 2009 at 3:17 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: