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

前端 未结 4 1806
萌比男神i
萌比男神i 2020-12-08 03:55

I have following test class

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


        
相关标签:
4条回答
  • 2020-12-08 04:24

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-08 04:27

    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() {
        }
    }
    
    0 讨论(0)
  • 2020-12-08 04:36

    This works fine too:

    @Autowired
    ApplicationContext context;
    
    0 讨论(0)
  • 2020-12-08 04:37

    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.

    0 讨论(0)
提交回复
热议问题