Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

junit

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?

like image 385
Edward Dale Avatar asked Aug 04 '10 12:08

Edward Dale


2 Answers

You can use a TestContextManager from Spring. In this example, I'm using Theories instead of Parameterized.

@RunWith(Theories.class)
@ContextConfiguration(locations = "classpath:/spring-context.xml")
public class SeleniumCase {
  @DataPoints
  public static WebDriver[] drivers() {
    return new WebDriver[] { firefoxDriver, internetExplorerDriver };
  }

  private TestContextManager testContextManager;

  @Autowired
  SomethingDao dao;

  private static FirefoxDriver firefoxDriver = new FirefoxDriver();
  private static InternetExplorerDriver internetExplorerDriver = new InternetExplorerDriver();

  @AfterClass
  public static void tearDown() {
    firefoxDriver.close();
    internetExplorerDriver.close();
  }

  @Before
  public void setUpStringContext() throws Exception {
    testContextManager = new TestContextManager(getClass());
    testContextManager.prepareTestInstance(this);
  }

  @Theory
  public void testWork(WebDriver driver) {
    assertNotNull(driver);
    assertNotNull(dao);
  }
}

I found this solution here : How to do Parameterized/Theories tests with Spring

like image 192
Simon LG Avatar answered Sep 29 '22 11:09

Simon LG


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
}
like image 26
Jeanne Boyarsky Avatar answered Sep 29 '22 11:09

Jeanne Boyarsky