Recently I had to write a couple of unit tests for a Java class which was delegating work to some collaborators. Typically a unit test for such a Java class involves mocking and verifying behavior of collaborators. Up until this point my existing mocking framework of choice in Java used to be mockito. Whereas having a code snippet like:
Would result in a unit test such as:
As there’s also Groovy available for usage in the code base I’m currently working on I thought, if there might be a better way to mock and verify behavior of collaborators. I also find the mockito library partially counterintuitive - especially around using the cumbersome
ArgumentCaptor. I always tend to forget the name of the class und its usage.
It turns out there’s an amazing mechanism called Map coercion in groovy which can be used for “mocking”.
The idea behind Map coercion is to coerce a map into a defined class.
In order for this mechanism to work the map keys have to match method names and there values are functions (or Closures in Groovy terms) which signatures have to match the matched method name signature.
The created class instance will then contain our “coerced” behavior.
In terms of Map coercion our preceding example would look like:
The test is now much more concise and doesn’t require an additional mocking library dependency. As a pretty nice side effect I also got rid of the type declaration of variables as these can be inferred by the compiler anyway. Also Groovy comes with a pretty nice test assertion mechanism out of the box where there’s not really an additional assertion library needed.