如何在使用@RunWith和@ContextConfiguration注释的jUnit测试中访问Spring上下文?
我有以下测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest {
@Autowired
MyService service;
...
}
是否可以通过其中一种方法以编程方式访问 services-test-config.xml
?喜欢:
ApplicationContext ctx = somehowGetContext();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这也很好用:
This works fine too:
由于测试也将像 Spring bean 一样实例化,因此您只需要实现 ApplicationContextAware 接口:
对于非 xml 需求,您也可以这样做:
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
For non xml needs, you can also do this:
如果您的测试类扩展了 Spring JUnit 类
(例如,
AbstractTransactionalJUnit4SpringContextTests
或任何其他扩展AbstractSpringContextTests
的类),您可以通过调用getContext()
方法来访问应用上下文。查看 org.springframework 包的 javadocs。测试。
If your test class extends the Spring JUnit classes
(e.g.,
AbstractTransactionalJUnit4SpringContextTests
or any other class that extendsAbstractSpringContextTests
), you can access the app context by calling thegetContext()
method.Check out the javadocs for the package org.springframework.test.
可以使用
SpringClassRule
注入ApplicationContext
类的实例和 SpringMethodRule 规则。如果您想使用它可能会非常方便
另一个非 Spring 跑步者。这是一个例子:
It's possible to inject instance of
ApplicationContext
class by usingSpringClassRule
and
SpringMethodRule
rules. It might be very handy if you would like to useanother non-Spring runners. Here's an example:
创建了一篇与此问题相关的帖子,这确实有助于获得信心
尝试此链接了解更多详细信息
Created one post related to this issue, this really helpful to gain confidence
Try this link for more details