如何在使用@RunWith和@ContextConfiguration注释的jUnit测试中访问Spring上下文?

Vla*_*mir 54 junit spring spring-test applicationcontext

我有以下测试课

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

  @Autowired
  MyService service;
...

}
Run Code Online (Sandbox Code Playgroud)

是否可以通过services-test-config.xml其中一种方法以编程方式访问?喜欢:

ApplicationContext ctx = somehowGetContext();
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 72

这也很好:

@Autowired
ApplicationContext context;
Run Code Online (Sandbox Code Playgroud)


Daf*_*aff 46

由于测试也将像Spring bean一样实例化,您只需要实现ApplicationContextAware接口:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止,在 Spring 3.0 及更高版本中不可能。 (2认同)

duf*_*ymo 7

如果您的测试类扩展了Spring JUnit类
(例如,AbstractTransactionalJUnit4SpringContextTests或任何其他扩展的类AbstractSpringContextTests),则可以通过调用该getContext()方法来访问应用程序上下文.
查看包org.springframework.test 的javadocs.