对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

测试的提前编译(AOT)支持

本章介绍 Spring 使用 Spring TestContext 框架对集成测试提供的预先编译(Ahead of Time,AOT)支持。spring-doc.cadn.net.cn

测试支持通过以下功能扩展了 Spring 的核心 AOT 支持spring-doc.cadn.net.cn

  • 在构建时检测当前项目中所有使用 TestContext 框架加载 ApplicationContext 的集成测试。spring-doc.cadn.net.cn

    • 为基于 JUnit Jupiter 和 JUnit 4 的测试类提供显式支持, 同时也为使用 Spring 核心测试注解的 TestNG 及其他测试框架提供隐式支持—— 前提是这些测试使用了为当前项目注册的 JUnit Platform TestEngine 来运行。spring-doc.cadn.net.cn

  • 构建时AOT处理:当前项目中的每个唯一的测试ApplicationContext都将为AOT处理而刷新spring-doc.cadn.net.cn

  • 运行时 AOT 支持:当在 AOT 运行时模式下执行时,Spring 集成测试将使用一个经过 AOT 优化的 ApplicationContext,该上下文会透明地参与上下文缓存spring-doc.cadn.net.cn

@ContextHierarchy 注解目前在 AOT 模式下不受支持。spring-doc.cadn.net.cn

为了在 GraalVM 原生镜像中提供特定于测试的运行时提示,您有以下几种选项。spring-doc.cadn.net.cn

TestRuntimeHintsRegistrar API 是核心 RuntimeHintsRegistrar API 的配套接口。如果你需要注册用于测试支持的全局提示(hints),且这些提示不针对特定的测试类,则应优先实现 RuntimeHintsRegistrar,而不是使用专用于测试的 API。spring-doc.cadn.net.cn

如果您实现了一个自定义的 ContextLoader,则必须实现 AotContextLoader, 以便提供 AOT 构建时处理和 AOT 运行时执行支持。但请注意, Spring Framework 和 Spring Boot 提供的所有上下文加载器实现都已经实现了 AotContextLoaderspring-doc.cadn.net.cn

如果您实现了一个自定义的 TestExecutionListener,则必须实现 AotTestExecutionListener 以便参与 AOT 处理。请参阅 spring-test 模块中的 SqlScriptsTestExecutionListener 以获取示例。spring-doc.cadn.net.cn