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

前端 未结 4 1812
萌比男神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
        }
    }
    

提交回复
热议问题