Search code examples
springjunitspring-testapplicationcontext

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?


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();

Solution

  • 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
        }
    }
    

    For non xml needs, you can also do this:

    @RunWith(SpringJUnit4ClassRunner.class)
    /* must provide some "root" for the app-context, use unit-test file name to the context is empty */
    @ContextConfiguration(classes = MyUnitTestClass.class)
    public class MyUnitTestClass implements ApplicationContextAware {