Monday, September 26, 2011

Groovy: Reuse of Helper Test Methods in a Spec

There are a lot of message transformers in a lot of the projects I work that work primarily with XML. I want my tests to take a source XML document and verify the output transformation. The example input and output messages live on the classpath, say in directory src/test/resources, and their contents are accessed through the classloader.

Take this example spec written for the Spock framework for Groovy:

    class XmlTransformerSpec extends Specification {

XmlTransformer transformer = new XmlTransformer()

def "transforms xml messages for some business goal"() {
given:
def inputXml = textOf("input.xml")
def expectedOutputXml = textOf("expected-output.xml")
when:
def actualOutputXml = transformer.transform(inputXml)
then:
areIdentical(expectedOutputXml, actualOutputXml)
}

def areIdentical(String expected, String actual) {
XMLUnit.setIgnoreWhitespace true
new Diff(expected, actual).identical()
}

def textOf(resource) {
getClass().getClassLoader().getResourceAsStream(resource).text
}

}

The retrieval of the messages in the form of resources is contained within the textOf() method where it can be resued by additional tests within the spec. What if I wanted to reuse it other test classes? One option I found was to move the method to an abstract class that extends spock.lang.Specification:

    abstract class ResourceAwareSpecification extends Specification {

def textOf(resource) {
getClass().getClassLoader().getResourceAsStream(resource).text
}
}

Now my test spec, along with any others that need to retrieve the contents of classpath resources, can extend the new specification:

    class XmlTransformerSpec extends ResourceAwareSpecification {
// method textOf() has been removed...
}

I wonder if others find themselves loading resources in this way and may make use of an approach like this if it were builtin to a framework like Spock in this or some other form, like a mixin. The helper method comparing the XML using XMLUnit would be another candidate in my mind for such an addition. Thoughts?

No comments:

Post a Comment