Let's look at an example of how using Groovy to
test your existing
Java code could cause significant gains...
So you have this nasty interface that needs to be mocked and injected into your class under test:
ComplicatedInterface.java
In order to create a mock or stub object for this, you'll need to implement three methods, one with a ResultSet, and one with several parameters. Bleck.
The
class under test is called Worker:
Worker.java
... and all we really want to test is that
uglyMethod calls some static utils class with the given interface implementation twice, then compares the results properly, returning true if the second number is greater than the first. For simplicity's sake, we'll make our static utils as dumb as possible:
DumbUtils.java
So if you want to test
Worker.uglyMethod using Java, it would be messy. You'd have to create a mock class that implements the
ComplicatedInterface, and it would have all those nasty method implementations. I know you've seen some interfaces with 17 required methods, each one more complicated than the other. I'm making it even simpler just by having three.
But let's not even bother to do this with Java. Let's do it the easy way: with Groovy...
WorkerTests.groovy
In case you missed it, the magic line is
We know the
class under test needs to call
DumbUtils.generateNumber, passing in the
ComplicatedInterface. In
DumbUtils, the interface's
methodThree is called to return an int value. So we've created a mock method in the form of a closure. In the first test, it starts at 0 and returns one greater on each call. In the second test, it goes one lesser. We are using this closure within a map to provide an implementation of the
ComplicatedInterface's
methodThree requirement. And because we are telling Groovy that
we want to treat this map "as" a ComplicatedInterface, it takes care of mocking out all the rest of the interface's implementation. Then that mock is injected into the class under test and is available during the test run.
This is a common antipattern in enterprise applications, and it can be frustrating to keep the tests focused on the code under test, instead of mocking out the state of the application to prepare for the test. Groovy can help provide shortcuts during testing that makes your tests more expressive and help you focus on the real task of your tests.