spring 如何在用@RunWith 和@ContextConfiguration 注释的jUnit 测试中访问Spring 上下文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2425015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?
提问by Vladimir
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.xmlprogrammatically in one of such methods? Like:
是否可以通过services-test-config.xml其中一种方法以编程方式访问?喜欢:
ApplicationContext ctx = somehowGetContext();
采纳答案by Daff
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
由于测试也将像 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
}
}
回答by axtavt
This works fine too:
这也很好用:
@Autowired
ApplicationContext context;
回答by duffymo
If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTestsor any other class that extends AbstractSpringContextTests), you can access the app context by calling the getContext()method.
Check out the javadocsfor the package org.springframework.test.
如果您的测试类扩展了 Spring JUnit 类
(例如,AbstractTransactionalJUnit4SpringContextTests或任何其他扩展类AbstractSpringContextTests),您可以通过调用该getContext()方法来访问应用程序上下文。
查看包 org.springframework.test的javadocs。
回答by Laplas
It's possible to inject instance of ApplicationContextclass by using SpringClassRuleand SpringMethodRulerules. It might be very handy if you would like to use
another non-Spring runners. Here's an example:
可以ApplicationContext通过使用SpringClassRule和SpringMethodRule规则注入类的实例。如果您想使用其他非 Spring 跑步者,这可能会非常方便。下面是一个例子:
@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() {
}
}

