Categories
java junit spring

How can I use the Parameterized JUnit test runner with a field that’s injected using Spring?

I’m using Spring to inject the path to a directory into my unit tests. Inside this directory are a number of files that should be used to generate test data for parameterized test cases using the Parameterized test runner. Unfortunately, the test runner requires that the method that provides the parameters be static. This doesn’t work for my situation because the directory can only be injected into a non-static field. Any ideas how I can get around this?

I assume you are using JUnit 4.X since you mentioned the Parameterized test runner. This implies you aren’t using @RunWith(SpringJUnit4ClassRunner). Not a problem, just listing my assumptions.

The following uses Spring to get the test files directory from the XML file. It doesn’t inject it, but the data is still available to your test. And in a static method no less.

The only disadvantage I see is that it may mean your Spring config is getting parsed/configured multiple times. You could load just a smaller file with test specific info if need be.

@RunWith(Parameterized.class)
public class MyTest {
@Parameters
public static Collection<Object[]> data() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("/jeanne/jeanne.xml");
String dir = ctx.getBean("testFilesDirectory", String.class);
// write java code to link files in test directory to the array
return Arrays.asList(new Object[][] { { 1 } });
}
// rest of test class
}