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

上下文管理

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

@Autowired ApplicationContext

作为实现ApplicationContextAware接口中,您可以注入 测试类的应用程序上下文,通过@Autowired注释 Field 或 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.

使用 Dependency injection@AutowiredDependencyInjectionTestExecutionListener,这是默认配置的 (参见 Dependency Injection of Test Fixtures)。spring-doc.cadn.net.cn

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

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