Monday, July 18, 2011

Testing and Groovin'

I've come to the conclusion that writing unit tests in Java is such a pain. Specially when there are others languages that are better suited for writing test. Lately, I've been writing all my test using Groovy. I have been using it for writing unit tests and creating mock objects. I am using EasyMock for most of my programming time, but I recently found out that Groovy has its own mock object framework. Here are some example from the site. I think that they are pretty compelling.

Domain Layer:

Service Layer:

This is the class that we are going to test. As you noticed, we are using the ExchangeRateService class.


Here we will need to mock the ExchangeRateService. We are going to use a few example that Groovy can provide us:
- You can often get away with simple maps or closures to build your custom mocks
- By using maps or expandos, we can incorporate desired behaviour of a collaborator very easily as shown here:

This is an example of using it with closure:

If we need the full power of a dynamic mocking framework, Groovy has a built-in framework which makes use of meta-programming to define the behaviour of the service. An example is shown here:

As I mentioned, just like any other mocking framework, Groovy has its own framework build-in: "MockFor" which defines the behavior of the collaborator.

Let me know how it goes and thanks for reading!

No comments:

Post a Comment