Simple and reusable data helper for Groovy unit testing

I recently created a little helper method for my Groovy unit tests that I’ve found helpful multiple times in the last week so I thought I should share. This little snippet will add a ‘prepare’ method to all objects which will help you build ‘mock’ unit test data.

You can use this helper like so:

This doesn’t seem all that amazing until you starting dealing with more complex objects. For instance, in the following example, we are able to reuse all of the default data for the person (height, age, eye color) but provide a custom list of children which might be a requirement for a test.

A couple of notes about this “helper method”:

  • You don’t have to pass in overrides. You can just call DEFAULT_CONFIG.prepare() and get a copy of the DEFAULT_CONFIG data. This will let you use the data without modifying the defaults.
  • I find it most useful to define default data maps as class level variables in my test class and then never modify them. I always use the prepare method to get an instance to use in the test, even if I don’t need to modify the data. For tests that use a lot of the same data with minor modifications, this makes each individual test method very short and easy to read.
Advertisements

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