此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

上下文管理

TestContext为测试实例提供上下文管理和缓存支持 它对此负责。测试实例不会自动接收对 配置ApplicationContext.但是,如果测试类实现了ApplicationContextAware接口,对ApplicationContext提供 到测试实例。请注意AbstractJUnit4SpringContextTestsAbstractTestNGSpringContextTests实现ApplicationContextAware因此, 提供对ApplicationContext自然而然。spring-doc.cadn.net.cn

@Autowired ApplicationContext

作为实现ApplicationContextAware接口,可以注入 测试类的应用程序上下文,通过@Autowired注释 字段或 setter 方法,如以下示例所示:spring-doc.cadn.net.cn

@SpringJUnitConfig
class MyTest {

	@Autowired (1)
	ApplicationContext applicationContext;

	// class body...
}
1 注入ApplicationContext.
@SpringJUnitConfig
class MyTest {

	@Autowired (1)
	lateinit var applicationContext: ApplicationContext

	// class body...
}
1 注入ApplicationContext.

同样,如果您的测试配置为加载WebApplicationContext,您可以注射 Web 应用程序上下文到测试中,如下所示:spring-doc.cadn.net.cn

@SpringJUnitWebConfig (1)
class MyWebAppTest {

	@Autowired (2)
	WebApplicationContext wac;

	// class body...
}
1 配置WebApplicationContext.
2 注入WebApplicationContext.
@SpringJUnitWebConfig (1)
class MyWebAppTest {

	@Autowired (2)
	lateinit var wac: WebApplicationContext
	// class body...
}
1 配置WebApplicationContext.
2 注入WebApplicationContext.

使用@AutowiredDependencyInjectionTestExecutionListener,默认配置 (请参阅测试夹具的依赖注入)。spring-doc.cadn.net.cn

使用 TestContext 框架的测试类不需要扩展任何特定的 类或实现特定接口来配置其应用程序上下文。相反 配置是通过声明@ContextConfiguration注释 班级级别。如果测试类未显式声明应用程序上下文资源 locations 或组件类,则配置的ContextLoader确定如何加载 上下文来自默认位置或默认配置类。除了上下文 资源位置和组件类,也可以配置应用程序上下文 通过应用程序上下文初始值设定项。spring-doc.cadn.net.cn

以下部分解释如何使用 Spring 的@ContextConfiguration注释到 配置测试ApplicationContext通过使用 XML 配置文件、Groovy 脚本、 组件类(通常@Configuration类)或上下文初始值设定项。 或者,您可以实现和配置自己的自定义SmartContextLoader为 高级用例。spring-doc.cadn.net.cn