Existing Groovy DSLs
[ 244 ]
JUnit
The Spock test framework is built on top of the JUnit test framework. If we were
to rewrite the preceding feature method in a JUnit test case, it might look a little
like this:
public class ChapterNineTest extends TestCase {
public void testStack() {
Stack stack = new Stack();
assert stack.size() == 0;
stack.push("elem");
assert stack.size() == 1;
assert stack.peek().equals("elem");
}
}
I've kept this simple as an old style JUnit test without annotations so that we can
start to use our knowledge of Groovy to imagine how a Spock-like DSL could be
achieved. It should be clear that the only way to achieve this would be by using a
Global AST transformation.
One possible way to achieve this using AST transformations would be to transform
the ChapterNineSpec class by extending it from TestCase. The feature method
would need to be transformed by creating a new method starting with test. Each of
the blocks would have to be cloned and injected into the new method in sequence
and each statement line in the then: block would need to have an AssertStatement
ASTNode object added to it.
In fact, this is not far removed from what Spock actually does do under the covers.
One important difference is that Spock does not actually try to transform the
Specification class into a test case class. This can be avoided because Spock
implements its own JUnit Runner class. This runner class understands how to
find each feature methods in turn and invokes it using Java reflection.
Spock creates a brand new feature method in the AST. It builds up the body of the
feature method from the blocks contained in the original Specification class,
and when it is done, it deletes the AST nodes for the original feature methods
from the AST.
http://www.ebook3000.com