tags:

views:

362

answers:

3

Is there a way to get a class that extends AbstractTransactionalJUnit4SpringContexts to play nicely with JUnit's own @RunWith(Parameterized.class), so that fields marked as Autowired get wired in properly?


@RunWith(Parameterized.class)
public class Foo extends AbstractTransactionalJUnit4SpringContextTests {

  @Autowired private Bar bar

  @Parameters public static Collection data() {
     // return parameters, following pattern in
     // http://junit.org/apidocs/org/junit/runners/Parameterized.html
  }


  @Test public void someTest(){
    bar.baz() //NullPointerException
  }


}
+1  A: 

No, you can't. The superclass has:

@RunWith(SpringJUnit4ClassRunner.class)

which assures that the tests are run within spring context. If you replace it, you are losing this.

What comes to my mind as an alternative is to extend SpringJunit4ClassRunner, provide your custom functionality there and use it with @RunWith(..). Thus you will have the spring context + your additional functionality. It will call super.createTest(..) and then perform additional stuff on the test.

Bozho
That's disappointing... thanks anyway.
James Kingsbery
@James Kingsbery see my update for an alternative
Bozho
Yeah, I came to the same conclusion (must be a good idea then).
James Kingsbery
+2  A: 

See http://jira.springframework.org/browse/SPR-5292 There is a solution.

Michal Moravcik
Nice! Thanks, that'll be a huge help.
James Kingsbery
+1  A: 

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

Simon LG
this option wouldn't support things like @BeforeTransaction, would it?
matt b