I have a class that consume an XML file and produce text output based on the input. Both the input and output are rather complex and the output can also include things not in the input: e.g. include timestamps and the results from live data that are not controlled by the input – with other words: the class is not a pure input-output transformation.
I would like to test the resulting text output using JUnit. As the produced text can vary in many different ways based on the input, I would like to be able to match specific parts of the output against some sort of template in each test. Each template should allow for some simple text substitutions and also for ranges in the text that should not be matched.
The question is whether any such frameworks already exists?
One very low-level possibility would be to use some fancy regular expressions to match the text, but I think these will be a bit too limited for our use as you don’t have enough context in regular expressions…
EDIT: Two comments:
- One of the functions of the class is the ability to do certain simple types of aggregation of data and calculations (e.g. sums) based on the input. This I would like to test, without testing the rest of the generated text output as well.
- I wish it was possible to make changes to the existing code base, but it is a very large chuck of legacy code that I really don’t want to refactor. So introduction of mock services or testing of smaller pieces will not be possible.
I would use Groovy for writing the unit tests, because this is one of Groovy’s strength, see
But Groovy is also superb for handling XML, see
A little example for summing up some XML attributes:
You can find a good tutorial about testing in the MEAP Making Java Groovy or look at this presentation.
Groovy has also template support. But with the XML support it is very easy to compare only certain attributes and not the whole tag content to skip some attributes like the timestamp you mentioned. Therefore you don’t need to compare templates. For an example add this source to the skript above:
To learn Groovy, I recommend the Groovy Koans. See also Adding Groovy Tests to a Maven Java Project.
Update:
I would not compare the XML against each other, instead I would unit test single values as desribed in my answer. But if you go the complete way I would use the following approach:
You can find an example on Updating XML with XmlSlurper the end of the page.