Loading Resources In Tests

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:

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.

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.

Posted in Clean Test Code, JUnit, JUnit Rule

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: