Ahead of Time Support for Tests

  • 构建时 AOT 处理每个独特的测试 ApplicationContext。

  • 运行时 AOT 支持,集成测试将使用参与上下文字符串的 AOT 优化 ApplicationContext。

本章介绍了 Spring Ahead of Time (AOT) 对使用 Spring TestContext Framework 的集成测试的支持。

测试支持扩展了 Spring 的 core AOT support,添加了以下功能。

  • 在当前项目中构建时检测所有集成测试都使用 TestContext 框架来加载一个 ApplicationContext

    • 明确支持基于 JUnit Jupiter 和 JUnit 4 的测试类,同时隐式支持 TestNG 和其他使用 Spring 的核心测试批注的测试框架 — 只要使用注册到当前项目的 JUnit Platform TestEngine 运行测试即可。

  • 构建时 AOT 处理:当前项目中每个独特的测试 ApplicationContext 都将会 refreshed for AOT processing

  • 运行时 AOT 支持:在 AOT 运行时模式下执行时,Spring 集成测试将使用与 context cache 透明参与的 AOT 优化的 ApplicationContext

默认情况下,所有测试都在 AOT 模式下启用。但是,您可以在 AOT 模式下通过使用 @DisabledInAotMode进行注释来有选择地禁用整个测试类或单个测试方法。在使用 JUnit Jupiter 时,您可以通过 Jupiter 的 @EnabledInNativeImage@DisabledInNativeImage 注释有选择地在 GraalVM nativeimage 中启用或禁用测试。请注意, @DisabledInAotMode 在运行 GraalVM nativeimage 时还会禁用带注释的测试类或测试方法,类似于 JUnit Jupiter 的 @DisabledInNativeImage 注释。

默认情况下,如果在构建时 AOT 处理期间遇到错误,将抛出异常,整个进程将立即失败。 如果您希望在遇到错误后继续构建时 AOT 处理,您可以禁用 failOnError 模式,这会导致错误以 WARN 级别记录,或以 DEBUG 级别更详细地记录。 可以通过将名为`spring.test.aot.processing.failOnError`的JVM系统属性设置为`false`来通过命令行或构建脚本禁用`failOnError`模式。另外,还可以通过SpringProperties机制设置相同的属性。

AOT 模式不支持 @ContextHierarchy 注释。

要为 GraalVM 原生映像中使用提供特定于测试的运行时提示,您可以选择以下选项。

  • 实现一个自定义https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/aot/TestRuntimeHintsRegistrar.html[TestRuntimeHintsRegistrar]并通过 META-INF/spring/aot.factories 全局注册它。

  • 实现一个自定义https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aot/hint/RuntimeHintsRegistrar.html[RuntimeHintsRegistrar]并通过 META-INF/spring/aot.factories 或通过https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ImportRuntimeHints.html[@ImportRuntimeHints] 在测试类中通过 META-INF/spring/aot.factories 来全局注册。

  • 用https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aot/hint/annotation/Reflective.html[@Reflective] 或https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aot/hint/annotation/RegisterReflectionForBinding.html[@RegisterReflectionForBinding]批注一个测试类。

  • 请参阅 Runtime Hints 了解 Spring 的核心运行时提示和批注支持的详细信息。

TestRuntimeHintsRegistrar API 作为核心 RuntimeHintsRegistrar API 的配套工具。如果您需要为特定于测试支持的测试注册全局提示,则优先实现 RuntimeHintsRegistrar 而不是特定于测试的 API。

如果您实现了一个自定义 ContextLoader,则它必须实现https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/aot/AotContextLoader.html[AotContextLoader] 才能提供 AOT 构建时处理和 AOT 运行时执行支持。不过,请注意,Spring Framework 和 Spring Boot 提供的所有上下午装载器实现都已实现了 AotContextLoader

如果您实现了一个自定义 TestExecutionListener,则它必须实现https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/aot/AotTestExecutionListener.html[AotTestExecutionListener] 才能参与 AOT 处理。请参阅 spring-test 模块中的 SqlScriptsTestExecutionListener 以获取示例。