Enter Groovy Builders
A builder is a type of DSL that allows object structures to be constructed in a syntax that is expressive within a particular problem domain. Groovy has builder support based on closures and meta-programming that provides a much more expressive syntax than has previously been available in the Java platform (see Listing 1
for an example).
The structure of the document created in Listing 1 is very clear and easy to understand. Here is the markup of the output it produces:
<p>Put the table here:</p>
The downloadable source code for this article provides all the code for the simple builder example.
So far, you have seen an expressive piece of code that can generate XHTML output. To test the code, you would still have to execute it and parse the output to ensure it is correct. To do this, you will need to refactor the example into a testable class that will implement the table-highlighting logic (see Listing 2).
Listing 2 implements the presentation logic to highlight alternate rows in a table, but because the builder is being constructed outside of this class, it also is now possible to test whether the correct logic is being performed by passing in a testing builder. There are a number of options for this:
- Use a basic NodeBuilder and then assert that the builder had the expected nodes in your test.
- Pass in a MarkupBuilder and use the Groovy XmlSlurper to verify that the correct XHTML had been constructed.
- Implement your own builder, upon which you can define expectations and then verify that the expectations have been met, in a similar approach to the EasyMock project.
Using the NodeBuilder would mean navigating through lots of child nodes just to get to the information you needed. XmlSlurper provides a very simple interface for parsing XML, which you can then perform GPath queries on to verify the structure is as expected (see Listing 3). While this approach is more elegant than using NodeBuilder, it is still much less clear than defining expectations and verifying them through your own builder (as the code in Listing 4 does).
In the first test (Listing 3), where the XML output is parsed, you can see that it is extremely simple to use Groovy to parse XML. However, this does not necessarily make the test easy to read. In the second example (Listing 4), the test is defining an ordered subset of the nodes you expect to be called and then using the builder for the execution and the verification that your expectations have been met.
You can download the source of AssertableBuilder in the source code for this article.