64

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();
Laplas
  • 537
  • 1
  • 6
  • 9
Vladimir
  • 11,563
  • 18
  • 58
  • 76
  • I'm pretty sure it is possible even with the vanilla runner `JUnit4.class`, which the answers are ignoring. I need to Google around a bit more. – Sridhar Sarnobat May 28 '19 at 18:01

4 Answers4

83

This works fine too:

@Autowired
ApplicationContext context;
axtavt
  • 228,184
  • 37
  • 489
  • 472
56

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 {
granadaCoder
  • 21,474
  • 7
  • 81
  • 117
Daff
  • 41,847
  • 9
  • 99
  • 113
8

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.

atish shimpi
  • 4,461
  • 1
  • 28
  • 46
duffymo
  • 293,097
  • 41
  • 348
  • 541
  • Is there any difference when using the AbstractTransactionalJUnit4SpringContextTests, or AbstractSpringContextTests vs simply extending ApplicationContextAware in my junit test? What benefits are provided by the 2 abstract test classes suggested in this answer? – Nelda.techspiress Feb 20 '17 at 20:02
2

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}
Laplas
  • 537
  • 1
  • 6
  • 9