Spring testing framework: how to load the application context from the file system

While attempting to standardize the testing of a code base, I’ve been trying to enable Spring’s test-level transaction management. In a nutshell, if you run a properly configured test within Spring’s test transaction framework then then the test does not actually commit anything to a database.

It should be as easy as annotating your test class like this:


This loads the application context from the classpath and then manipulates the transaction manager named myTxManager to roll back the database transaction when the test is complete. The problem I have is that the application context file isn’t on the classpath. To make it even more interesting, it’s stored on a different place on each developer workstation. There’s already a utility to discover the file, I just need to hook it into the context loader.

After reading this, it became apparent that what I wanted was to write my own context loader. All that’s needed is to change the location(s) to include the file path (plus a file: prefix) so that the resource loader can locate the files.

public class MyContextLoader extends GenericXmlContextLoader {
    protected String[] modifyLocations(Class<?> clazz, String... locations) {
        String[] modifiedLocations = new String[locations.length];
        for (int i = 0; i < locations.length; i++) {
            modifiedLocations[i] = "file:" 
                + FileLocator.getApplicationContextDir() 
                + "/" + locations[i]; 
        return modifiedLocations;

And then I change one line in the test class annotation:

@ContextConfiguration(locations="application-context.xml", loader=MyContextLoader.class)

Now the test will look in the appropriate location on each developer’s machine and load the application context file properly.