java 使用@RunWith(SpringJUnit4ClassRunner.class),可以访问ApplicationContext对象吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14822730/
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
Using @RunWith(SpringJUnit4ClassRunner.class), can you access the ApplicationContext object?
提问by egervari
I have a Spring test that uses:
我有一个 Spring 测试,它使用:
@RunWith(SpringJUnit4ClassRunner.class)
Unlike the older way of testing, extending from the Spring test base classes, there appears to be no obvious way to access to the ApplicationContext that has been loaded by Spring using @ContextConfiguration
与从 Spring 测试基类扩展的旧测试方式不同,似乎没有明显的方法可以访问 Spring 加载的 ApplicationContext 使用 @ContextConfiguration
How can I access the ApplicationContext
object from my test methods?
如何ApplicationContext
从我的测试方法访问对象?
Thanks!
谢谢!
回答by Mark
From the Integration Testingsection of the Spring Documentation
来自Spring 文档的集成测试部分
@Autowired ApplicationContext
As an alternative to implementing the ApplicationContextAware interface, you can inject the application context for your test class through the @Autowired annotation on either a field or setter method. For example:
@Autowired 应用程序上下文
作为实现 ApplicationContextAware 接口的替代方法,您可以通过字段或 setter 方法上的 @Autowired 注释为您的测试类注入应用程序上下文。例如:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {
@Autowired
private ApplicationContext applicationContext;
// class body...
}
回答by Dave G
Add an @Autowired attribute of ApplicationContext
添加ApplicationContext的@Autowired属性
@Autowired ApplicationContext applicationContext;
回答by nizar ouerghi
I use this:
我用这个:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyClassTest
{
}
and go to project build path -> Source ->
add the location of your applicationContext.xml
并转到项目构建路径-> Source ->
添加您的位置applicationContext.xml
I use maven so the applicationContext.xml
is under src/main/resources
.
我使用 maven 所以applicationContext.xml
在src/main/resources
.
If you use this method you can have a multiple applicationContext for testing for example :
如果您使用此方法,您可以有多个 applicationContext 进行测试,例如:
@ContextConfiguration("classpath:applicationContext_Test.xml")
or
或者
@ContextConfiguration("classpath:applicationContext_V01.xml")