Saturday, February 9, 2013

Hard-coded XML in Unit Test code

Everyone knows that unit tests should be as self-contained as possible. Everything that is needed to run the unit test should be contained within the unit test class itself. It should rely as little as possible on other resources, such as files or database connections. This makes them easier to maintain, and makes them less susceptible to the failures of these external systems.

So what happens when your unit test needs some large block of text, like an XML document, to run? You might be tempted to put it in a separate file, but this goes against the self-containability principle described above. You might consider including them as hard-coded strings, but this isn't the best approach either. Java doesn't have a multi-line string syntax like most other languages, so doing this will strip away all the formatting that makes the XML document human-readable.

String xml = "<library><wifi>true</wifi><book><title>The Hunger Games</title><author>Suzanne Collins</author></book></library>";

By contrast, this same XML document could be defined in PHP as a multi-line string.

$xml = <<<XML
    <title>The Hunger Games</title>
    <author>Suzanne Collins</author>

As you can see, the XML document in the PHP code is much more readable than the XML document in the Java code.

Despite Java not supporting multi-line strings, there is still a way that they can be mimicked. The string can be split up into multiple substrings that can be arranged however you want. These substrings are then concatenated together to form the final string.

String xml =
"<library>" +
  "<wifi>true</wifi>" +
  "<book>" +
    "<title>The Hunger Games</title>" +
    "<author>Suzanne Collins</author>" +
  "</book>" +

If you use the code-formatting functionality provided by an IDE, you must remember to instruct the IDE not to format this block of code. Eclipse uses a @formatter:off/on pair of comments to accomplish this (the setting for which must be manually enabled in the code formatting preferences).