Sunday, October 11, 2009

Combining TemporaryFolder @Rule with Spring 3

I like TDD, I like Springs @ContextConfiguration framework and I like JUnit 4.7's new Temporary folder. Getting the latter two to play nice isn't as easy as I hoped, so here's an attempt at a way to make them work.

Let's say you need to configure an incoming directory on a component using external configuration. For example in Spring Integration: <file:inbound-channel-adapter directory=#{} ... />.

I'm using expression language to load a property from a config object, which I wire in turn as a Spring bean. In my main application this config object can just be a for example, and in my test I can override that bean with an inner class from my test.

public static class Config {
public static final Map directories = new HashMap();

If you then use the containing context in a JUnit test it will be loaded up once the context is created, so you need to make sure to put the store value in the map @BeforeClass. Now I'd like to use a TemporaryFolder, to store files in the input directory of the channel adapter, but you can't refresh the property of a singleton bean each test. The @Rule will be applied before each test, resulting in the second test using a different directory from the context. A shame.

A working solution is to just remove the @Rule annotation from the TemporaryFolder and manually invoke create() and delete(). I'd like to know if there is a better solution.

Maven sample project can be found on GitHub.

If you give it a go, let me know if you find a neater option!

No comments: