Saturday, May 11, 2013

Loading Classpath Resources from a Static Context

Recently, I had to figure out how to load classpath resources from within a static method in a test class. I've been doing it from a non-static method forever, but had to do some searching to figure out how to do it from a static method.

For example to build a scenario where one might want to do this, let's take a generic Record class that is used by many of our classes under test. As JSON is the input method for records from the user of our system, it might make sense to store our records to use during our tests as JSON test resources.

During our tests, we can load the record JSON from a test resource on the classpath with a test helper class like the below. The Groovy test class uses the ObjectMapper class from Jackson:

class RecordBuilder {
    def recordFor(resource) {
        new ObjectMapper().readValue textOf(resource), Record.class
    }
    def textOf(resource) {
        getClass().getClassLoader().getResourceAsStream(resource).text
    }
}

One annoyance with using the above class in our test classes is that each test class would need to create or be given an instance of RecordBuilder to do its work. An alternative is to make the record-building method static, which should be ok since the normal concerns regarding static methods, pro or con, should not apply in a testing scenario as tests are usually executed one at at time.

The problem with making the recordFor method static is the approach to reading the resource from the classpath no longer works, and the solution may not be apparent to those who have not tried to do something similar before. Below includes the answer I was able to find, referring to the RecordBuilder class itself:

class RecordBuilder {
    static def recordFor(resource) {
        new ObjectMapper().readValue textOf(resource), Record.class
    }
    static def textOf(resource) {
        RecordBuilder.class.getClassLoader().getResourceAsStream(resource).text
    }
}

I guess this was a rather long-winded way to show how to load classpath resources from a static context, but I hope it will do. Thanks.

No comments:

Post a Comment