使用@RunWith(SpringJUnit4ClassRunner.class),可以访问ApplicationCon



我有一个Spring测试,它使用:

@RunWith(SpringJUnit4ClassRunner.class)

与从Spring测试基类扩展而来的旧测试方法不同,似乎没有明显的方法可以访问Spring使用@ContextConfiguration 加载的ApplicationContext

如何从我的测试方法访问ApplicationContext对象?

谢谢!

来自Spring文档的集成测试部分

@自动连线应用程序上下文

作为实现ApplicationContextAware接口的替代方案,您可以通过字段或setter方法上的@Autowired注释为测试类注入应用程序上下文。例如:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {
  @Autowired
  private ApplicationContext applicationContext;
  // class body...
}

添加ApplicationContext 的@Autowired属性

@Autowired ApplicationContext applicationContext;

我使用这个:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyClassTest
{
}

并转到项目构建路径-> Source ->添加您的applicationContext.xml 的位置

我使用maven,所以applicationContext.xmlsrc/main/resources之下。

如果你使用这个方法,你可以有一个多应用程序上下文进行测试例如:

@ContextConfiguration("classpath:applicationContext_Test.xml")

@ContextConfiguration("classpath:applicationContext_V01.xml")

最新更新