Oftentimes in my unit tests I have fixtures that are read from resource files and stored into a static attribute on the test class:
public class TestFoo {
private static String fileContents;
@BeforeClass
public static void setup() throws IOException {
fileContents = ... read TestFoo.class.getResourceAsStream("filename") ...
}
}
Which works, but the problem I have is that I generally don't like non-final static data in my tests as it allows for the possibility of one test case to affect the output of another (in the above example if one test reassigned fileContents
to something else, then there would be side-effects in other tests that make use of the fixture data).
If I add the final modifier though, then the assignment has to happen at declaration, which is a problem when the initialization is non-trivial (such as in the above example where a checked exception could be triggered by the initialization code). An alternative is to use a static initializer block:
public class TestFoo {
private final static String fileContents;
static {
try {
fileContents = ... read TestFoo.class.getResourceAsStream("filename") ...
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
But I don't particularly like this approach due to the verbosity of having to write a try/catch.
Which approach is more common/idiomatic Java, or is there a better/more typical way to have a static final resource initialized?