views:

271

answers:

3

I have following test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest {

  @Autowired
  MyService service;
...

}

Is it possible to access services-test-config.xml programmatically in one of such methods? Like:

ApplicationContext ctx = somehowGetContext();
+2  A: 

Since the tests will be instantiated like a Spring bean, too you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}
Daff
+1  A: 

If your test class extends the Spring JUnit classes (e.g., AbstractTransactionalJUnit4SpringContextTests or any other class that extends AbstractSpringContextTests), you can access the app context by calling the getContext() method. Check out the javadocs for the package org.springframework.test.

duffymo
+6  A: 

This works fine too:

@Autowired
ApplicationContext context;
axtavt