Some level of tests, let’s call it integration testing because it’s not technically unit testing, often need to load resources like XML samples from the file system.
A talented developer I worked with recently, came up with this nice use of a JUnit Rule to clean up the resource loading, making it reusable and removing the irrelevant detail from the test classes. He also made it cope with different types of resources from simple Strings to XML documents.
Simply include your rule like this:
@Rule public TestResourceRule resources = new TestResourceRule(this);
Creating a Rule like that is pretty simple. See https://github.com/junit-team/junit/wiki/Rules
Then you can annotate the fields that should be created from some resource, like this.
@TestResource("xml-sample.xml") private Document xmlDocument;
Now you can just use that Document in your test, and neither you nor your future readers have to even see any file loading code. Nice.
Leave a Reply