This section covers annotations that you can use when you test Spring applications. It includes the following topics:
本节涵盖了您在测试 Spring 应用程序时可以使用的注释。它包括以下主题:
3.4.1. Spring 测试注解
The Spring Framework provides the following set of Spring-specific annotations that you can use in your unit and
integration tests in conjunction with the TestContext framework.
Spring 框架提供以下一组特定于 Spring 的注解,您可以在使用 TestContext 框架的单元测试和集成测试中使用这些注解。
See the corresponding javadoc for further information, including default attribute values, attribute aliases, and other
details.
查看相应的 javadoc 以获取更多信息,包括默认属性值、属性别名和其他细节。
Spring’s testing annotations include the following:
春季的测试注解包括以下内容:
@BootstrapWith@BootstrapWith is a class-level annotation that you can use to configure how the Spring TestContext Framework is
bootstrapped. Specifically, you can use @BootstrapWith to specify a custom TestContextBootstrapper. See the section
on bootstrapping the TestContext framework for further details.
@BootstrapWith 是一个类级别的注解,您可以使用它来配置如何引导 Spring TestContext 框架。具体来说,您可以使用
@BootstrapWith 来指定自定义的 TestContextBootstrapper 。有关引导 TestContext 框架的详细信息,请参阅相关章节。
@ContextConfiguration@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an
ApplicationContext for integration tests. Specifically, @ContextConfiguration declares the application context
resource locations or the component classes used to load the context.
@ContextConfiguration 定义类级别元数据,用于确定如何加载和配置用于集成测试的 ApplicationContext 。具体来说,
@ContextConfiguration 声明了用于加载上下文的资源 locations 或组件 classes 。
Resource locations are typically XML configuration files or Groovy scripts located in the classpath, while component
classes are typically @Configuration classes. However, resource locations can also refer to files and scripts in the
file system, and component classes can be @Component classes, @Service classes, and so on.
See Component Classes for further details.
资源位置通常是位于类路径中的 XML 配置文件或 Groovy 脚本,而组件类通常是 @Configuration 类。然而,资源位置也可以指代文件系统中的文件和脚本,组件类可以是
@Component 类、 @Service 类等等。有关详细信息,请参阅组件类。
The following example shows a @ContextConfiguration annotation that refers to an XML file:
以下示例显示了一个指向 XML 文件的 @ContextConfiguration 注释:
1
Referring to an XML file.
引用 XML 文件。
1
Referring to an XML file.
The following example shows a @ContextConfiguration annotation that refers to a class:
以下示例显示了一个指向类的 @ContextConfiguration 注释:
1
Referring to a class. 引用一个类。
As an alternative or in addition to declaring resource locations or component classes, you can use
@ContextConfiguration to declare ApplicationContextInitializer classes. The following example shows such a case:
作为声明资源位置或组件类的替代或补充,您可以使用 @ContextConfiguration 来声明 ApplicationContextInitializer
类。以下示例展示了这种情况:
1
Declaring an initializer class.
声明一个初始化器类。
1
Declaring an initializer class.
You can optionally use @ContextConfiguration to declare the ContextLoader strategy as well. Note, however, that you
typically do not need to explicitly configure the loader, since the default loader supports initializers and either
resource locations or component classes.
您可以选择使用 @ContextConfiguration 来声明 ContextLoader 策略。请注意,然而,通常您不需要显式配置加载器,因为默认加载器支持
initializers 以及资源 locations 或组件 classes 。
The following example uses both a location and a loader:
以下示例同时使用了一个位置和一个加载器:
1
Configuring both a location and a custom loader.
配置一个位置和自定义加载器。
1
Configuring both a location and a custom loader.
@ContextConfiguration provides support for inheriting resource locations or configuration classes as well as context
initializers that are declared by superclasses or enclosing classes.
@ContextConfiguration 提供了对继承资源位置或配置类以及由超类或封装类声明的上下文初始化器的支持。
See Context Management,
@Nested test class configuration, and the
@ContextConfiguration javadocs for further details.
查看上下文管理, @Nested 测试类配置,以及 @ContextConfiguration javadoc 获取更多详细信息。
@WebAppConfiguration@WebAppConfiguration is a class-level annotation that you can use to declare that the ApplicationContext loaded for
an integration test should be a WebApplicationContext. The mere presence of @WebAppConfiguration on a test class
ensures that a WebApplicationContext is loaded for the test, using the default value of "file:src/main/webapp" for
the path to the root of the web application (that is, the resource base path). The resource base path is used behind the
scenes to create a MockServletContext, which serves as the ServletContext for the test’s WebApplicationContext.
@WebAppConfiguration 是一个类级别的注解,您可以使用它来声明为集成测试加载的 ApplicationContext 应该是
WebApplicationContext 。测试类上仅存在 @WebAppConfiguration 就可以确保为测试加载一个 WebApplicationContext ,使用
"file:src/main/webapp" 的默认值作为 Web 应用程序根目录的路径(即资源基本路径)。资源基本路径在幕后用于创建一个
MockServletContext ,它作为测试的 ServletContext 。
The following example shows how to use the @WebAppConfiguration annotation:
以下示例展示了如何使用 @WebAppConfiguration 注解:
1
The @WebAppConfiguration annotation.@WebAppConfiguration 注解。
1
Specifying a classpath resource.
To override the default, you can specify a different base resource path by using the implicit value attribute. Both
classpath: and file: resource prefixes are supported. If no resource prefix is supplied, the path is assumed to be a
file system resource. The following example shows how to specify a classpath resource:
要覆盖默认设置,您可以通过使用隐式的 value 属性来指定不同的基本资源路径。支持 classpath: 和 file:
资源前缀。如果没有提供资源前缀,则假定路径是文件系统资源。以下示例展示了如何指定类路径资源:
1
Specifying a classpath resource.
指定类路径资源。
Note that @WebAppConfiguration must be used in conjunction with @ContextConfiguration, either within a single test
class or within a test class hierarchy. See the
@WebAppConfiguration
javadoc for further details.
请注意, @WebAppConfiguration 必须与 @ContextConfiguration 结合使用,无论是在单个测试类中还是在测试类层次结构中。有关详细信息,请参阅
@WebAppConfiguration javadoc。
@ContextHierarchy@ContextHierarchy is a class-level annotation that is used to define a hierarchy of ApplicationContext instances for
integration tests. @ContextHierarchy should be declared with a list of one or more @ContextConfiguration instances,
each of which defines a level in the context hierarchy. The following examples demonstrate the use of
@ContextHierarchy within a single test class (@ContextHierarchy can also be used within a test class hierarchy):
@ContextHierarchy 是一个类级别注解,用于定义用于集成测试的 ApplicationContext 实例的层次结构。 @ContextHierarchy
应该使用一个包含一个或多个 @ContextConfiguration 实例的列表进行声明,每个实例定义上下文层次结构中的一个级别。以下示例演示了在单个测试类(
@ContextHierarchy 也可以在测试类层次结构中使用)中 @ContextHierarchy 的使用:
If you need to merge or override the configuration for a given level of the context hierarchy within a test class
hierarchy, you must explicitly name that level by supplying the same value to the name attribute in
@ContextConfiguration at each corresponding level in the class hierarchy.
See Context Hierarchies and the
@ContextHierarchy
javadoc for further examples.
如果您需要在测试类层次结构中合并或覆盖上下文字层次结构中给定级别的配置,您必须通过在每个相应级别的
@ContextConfiguration 中提供相同的值来显式命名该级别,以 name 属性。有关更多示例,请参阅上下文字层次结构和
@ContextHierarchy javadoc。
@ActiveProfiles@ActiveProfiles is a class-level annotation that is used to declare which bean definition profiles should be active
when loading an ApplicationContext for an integration test.
@ActiveProfiles 是一个类级别注解,用于声明在加载一个用于集成测试的 ApplicationContext 时应该激活哪些 bean 定义配置文件。
The following example indicates that the dev profile should be active:
以下示例表明应激活 dev 配置文件:
1
Indicate that the dev profile should be active.
指示 dev 配置文件应处于活动状态。
1
Indicate that the dev profile should be active.
The following example indicates that both the dev and the integration profiles should be active:
以下示例表明, dev 和 integration 配置文件都应该处于活动状态:
1
Indicate that the dev and integration profiles should be active.
指示 dev 和 integration 配置文件应处于活动状态。
1
Indicate that the dev and integration profiles should be active.
@ActiveProfiles provides support for inheriting active bean definition profiles declared by superclasses and enclosing
classes by default. You can also resolve active bean definition profiles programmatically by implementing a custom
ActiveProfilesResolver and registering it by using
the resolver attribute of @ActiveProfiles.
@ActiveProfiles 默认提供支持继承父类和封装类声明的活动 Bean 定义配置。您还可以通过实现自定义的 ActiveProfilesResolver
并使用 @ActiveProfiles 的 resolver 属性进行注册来程序化地解决活动 Bean 定义配置。
See Context Configuration with Environment Profiles,
@Nested test class configuration, and the
@ActiveProfiles
javadoc for examples and further details.
查看环境配置与配置文件, @Nested 测试类配置,以及 @ActiveProfiles Javadoc 以获取示例和更多详细信息。
@TestPropertySource@TestPropertySource is a class-level annotation that you can use to configure the locations of properties files and
inlined properties to be added to the set of PropertySources in the Environment for an ApplicationContext loaded
for an integration test.
@TestPropertySource 是一个类级别的注解,您可以使用它来配置要添加到 Environment 中 PropertySources
集合的属性文件和内联属性的位置,以便为集成测试加载的 ApplicationContext 配置。
The following example demonstrates how to declare a properties file from the classpath:
以下示例演示了如何从类路径中声明一个属性文件:
1
Get properties from test.properties in the root of the classpath.
从类路径根目录获取 test.properties 的属性。
1
Get properties from test.properties in the root of the classpath.
The following example demonstrates how to declare inlined properties:
以下示例演示了如何声明内联属性:
1
Declare timezone and port properties.
声明 timezone 和 port 属性。
1
Declare timezone and port properties.
See Context Configuration with Test Property Sources for examples and
further details.
查看带有测试属性源的上下文配置示例和更多详细信息。
@DynamicPropertySource@DynamicPropertySource is a method-level annotation that you can use to register dynamic properties to be added to
the set of PropertySources in the Environment for an ApplicationContext loaded for an integration test. Dynamic
properties are useful when you do not know the value of the properties upfront – for example, if the properties are
managed by an external resource such as for a container managed by the Testcontainers
project.
@DynamicPropertySource 是一种方法级注解,您可以使用它将动态属性注册到为集成测试加载的 ApplicationContext 的
Environment 集合中。当您事先不知道属性值时,动态属性很有用 - 例如,如果属性由外部资源管理,如由 Testcontainers 项目管理的容器。
The following example demonstrates how to register a dynamic property:
以下示例演示了如何注册动态属性:
1
Annotate a static method with @DynamicPropertySource.
注释一个 static 方法为 @DynamicPropertySource 。
2
Accept a DynamicPropertyRegistry as an argument.
接受一个 DynamicPropertyRegistry 作为参数。
3
Register a dynamic server.port property to be retrieved lazily from the server.
注册一个动态的 server.port 属性,从服务器中懒加载获取。
1
Annotate a static method with @DynamicPropertySource.
2
Accept a DynamicPropertyRegistry as an argument.
3
Register a dynamic server.port property to be retrieved lazily from the server.
See Context Configuration with Dynamic Property Sources for
further details.
查看动态属性源配置的上下文配置以获取更多详细信息。
@DirtiesContext@DirtiesContext indicates that the underlying Spring ApplicationContext has been dirtied during the execution of a
test (that is, the test modified or corrupted it in some manner — for example, by changing the state of a singleton
bean) and should be closed.
@DirtiesContext 表示在测试执行过程中,底层的 Spring ApplicationContext 被污染(即测试以某种方式修改或损坏了它——例如,通过改变单例
bean 的状态)并应关闭。
When an application context is marked as dirty, it is removed from the testing framework’s cache and closed. As a
consequence, the underlying Spring container is rebuilt for any subsequent test that requires a context with the same
configuration metadata.
当一个应用程序上下文被标记为脏时,它将从测试框架的缓存中移除并关闭。因此,对于任何需要具有相同配置元数据的上下文的后续测试,都会重新构建底层的
Spring 容器。
You can use @DirtiesContext as both a class-level and a method-level annotation within the same class or class
hierarchy. In such scenarios, the ApplicationContext is marked as dirty before or after any such annotated method as
well as before or after the current test class, depending on the configured methodMode and classMode.
您可以在同一个类或类层次结构中,将 @DirtiesContext 用作类级别和方法级别的注解。在这种情况下, ApplicationContext
在标注的任何此类方法之前或之后,以及在当前测试类之前或之后被标记为脏,具体取决于配置的 methodMode 和 classMode 。
The following examples explain when the context would be dirtied for various configuration scenarios:
以下示例解释了在哪些配置场景下上下文会被污染:
Before the current test class, when declared on a class with class mode set to BEFORE_CLASS.
在当前测试类之前,当在设置为 BEFORE_CLASS 类的模式下声明时。
1
Dirty the context before the current test class.
清理当前测试类之前的上下文。
1
Dirty the context before the current test class.
After the current test class, when declared on a class with class mode set to AFTER_CLASS (i.e., the default class
mode).
当前测试类之后,当在设置为 AFTER_CLASS (即默认类模式)的类上声明时。
1
Dirty the context after the current test class.
清理当前测试类之后的上下文。
1
Dirty the context after the current test class.
Before each test method in the current test class, when declared on a class with class mode set to
BEFORE_EACH_TEST_METHOD.
在每个当前测试类中的测试方法之前,当在设置为 BEFORE_EACH_TEST_METHOD. 类模式的类上声明时
1
Dirty the context before each test method.
在每次测试方法之前清理上下文。
1
Dirty the context before each test method.
After each test method in the current test class, when declared on a class with class mode set to
AFTER_EACH_TEST_METHOD.
在每个当前测试类中的测试方法之后,当在设置为 AFTER_EACH_TEST_METHOD. 类模式的类上声明时
1
Dirty the context after each test method.
测试后清理上下文。
1
Dirty the context after each test method.
Before the current test, when declared on a method with the method mode set to BEFORE_METHOD.
在当前测试之前,当在设置方法模式为 BEFORE_METHOD 的方法上声明时。
1
Dirty the context before the current test method.
清洗当前测试方法之前的上下文。
1
Dirty the context before the current test method.
After the current test, when declared on a method with the method mode set to AFTER_METHOD (i.e., the default method
mode).
当前测试之后,当在设置为 AFTER_METHOD (即默认方法模式)的方法上声明时。
1
Dirty the context after the current test method.
清理当前测试方法之后的上下文。
1
Dirty the context after the current test method.
If you use @DirtiesContext in a test whose context is configured as part of a context hierarchy with
@ContextHierarchy, you can use the hierarchyMode flag to control how the context cache is cleared. By default, an
exhaustive algorithm is used to clear the context cache, including not only the current level but also all other context
hierarchies that share an ancestor context common to the current test. All ApplicationContext instances that reside in
a sub-hierarchy of the common ancestor context are removed from the context cache and closed. If the exhaustive
algorithm is overkill for a particular use case, you can specify the simpler current level algorithm, as the following
example shows.
如果您在一个配置为与 @ContextHierarchy 构成上下文层次结构的测试中使用 @DirtiesContext ,您可以使用 hierarchyMode
标志来控制上下文缓存如何被清除。默认情况下,使用一种详尽的算法来清除上下文缓存,包括不仅当前级别,还包括所有与当前测试共享祖先上下文的上下文层次结构。所有位于共同祖先上下文子层次结构中的
ApplicationContext 实例都将从上下文缓存中移除并关闭。如果详尽算法对于特定用例来说过于强大,您可以指定更简单的当前级别算法,如下例所示。
1
Use the current-level algorithm.
使用当前级别的算法。
1
Use the current-level algorithm.
For further details regarding the EXHAUSTIVE and CURRENT_LEVEL algorithms, see the
DirtiesContext.HierarchyMode
javadoc.
有关 EXHAUSTIVE 和 CURRENT_LEVEL 算法的更多详细信息,请参阅 DirtiesContext.HierarchyMode javadoc。
@TestExecutionListeners@TestExecutionListeners is used to register listeners for a particular test class, its subclasses, and its nested
classes. If you wish to register a listener globally, you should register it via the automatic discovery mechanism
described in TestExecutionListener Configuration.
@TestExecutionListeners 用于注册特定测试类的监听器、其子类以及嵌套类。如果您希望全局注册监听器,应通过
TestExecutionListener 配置中描述的自动发现机制进行注册。
The following example shows how to register two TestExecutionListener implementations:
以下示例展示了如何注册两个 TestExecutionListener 实现:
1
Register two TestExecutionListener implementations.
注册两个 TestExecutionListener 实现。
1
Register two TestExecutionListener implementations.
By default, @TestExecutionListeners provides support for inheriting listeners from superclasses or enclosing classes.
See @Nested test class configuration and the
@TestExecutionListeners javadoc
for an example and further details. If you discover that you need to switch back to using the default
TestExecutionListener implementations, see the note in Registering
TestExecutionListener Implementations.
默认情况下, @TestExecutionListeners 提供了从超类或封装类继承监听器的支持。请参阅 @Nested 测试类配置和
@TestExecutionListeners javadoc 以获取示例和更多详细信息。如果您发现需要切换回使用默认的 TestExecutionListener
实现,请参阅注册 TestExecutionListener 实现中的说明。
@RecordApplicationEvents@RecordApplicationEvents is a class-level annotation that is used to instruct the Spring TestContext Framework to
record all application events that are published in the ApplicationContext during the execution of a single test.
@RecordApplicationEvents 是一个类级别的注解,用于指导 Spring TestContext 框架在单个测试执行期间记录在
ApplicationContext 中发布的所有应用程序事件。
The recorded events can be accessed via the ApplicationEvents API within tests.
记录的事件可以通过测试中的 ApplicationEvents API 进行访问。
See Application Events and the
@RecordApplicationEvents javadoc
for an example and further details.
查看应用程序事件和 @RecordApplicationEvents javadoc 以获取示例和更多详细信息。
@Commit@Commit indicates that the transaction for a transactional test method should be committed after the test method has
completed. You can use @Commit as a direct replacement for @Rollback(false) to more explicitly convey the intent of
the code. Analogous to @Rollback, @Commit can also be declared as a class-level or method-level annotation.
@Commit 表示在事务性测试方法完成后,应该提交该事务。您可以使用 @Commit 作为 @Rollback(false) 的直接替换,以更明确地传达代码意图。类似于
@Rollback , @Commit 也可以声明为类级别或方法级别的注解。
The following example shows how to use the @Commit annotation:
以下示例展示了如何使用 @Commit 注解:
1
Commit the result of the test to the database.
提交测试结果到数据库。
1
Commit the result of the test to the database.
@Rollback@Rollback indicates whether the transaction for a transactional test method should be rolled back after the test
method has completed. If true, the transaction is rolled back. Otherwise, the transaction is committed (see also
@Commit). Rollback for integration tests in the Spring TestContext Framework
defaults to true even if @Rollback is not explicitly declared.
@Rollback 表示在事务性测试方法完成后是否应该回滚事务。如果为 true ,则事务将回滚。否则,事务将提交(另见 @Commit
)。即使在未显式声明 @Rollback 的情况下,Spring TestContext Framework 中的集成测试回滚默认为 true 。
When declared as a class-level annotation, @Rollback defines the default rollback semantics for all test methods
within the test class hierarchy. When declared as a method-level annotation, @Rollback defines rollback semantics for
the specific test method, potentially overriding class-level @Rollback or @Commit semantics.
当作为类级别注解声明时, @Rollback 定义了测试类层次结构中所有测试方法的默认回滚语义。当作为方法级别注解声明时,
@Rollback 定义了特定测试方法的回滚语义,可能覆盖类级别的 @Rollback 或 @Commit 语义。
The following example causes a test method’s result to not be rolled back (that is, the result is committed to the
database):
以下示例导致测试方法的返回结果不会被回滚(即,结果会被提交到数据库中):
1
Do not roll back the result.
不要回滚结果。
1
Do not roll back the result.
@BeforeTransaction@BeforeTransaction indicates that the annotated void method should be run before a transaction is started, for test
methods that have been configured to run within a transaction by using Spring’s @Transactional annotation.
@BeforeTransaction methods are not required to be public and may be declared on Java 8-based interface default
methods.
@BeforeTransaction 表示应在开始事务之前运行标注为 void 的方法,对于通过使用 Spring 的 @Transactional
注解配置为在事务中运行测试方法。 @BeforeTransaction 方法不需要是 public ,并且可以声明在基于 Java 8 的接口默认方法上。
The following example shows how to use the @BeforeTransaction annotation:
以下示例展示了如何使用 @BeforeTransaction 注解:
1
Run this method before a transaction.
在事务之前运行此方法。
1
Run this method before a transaction.
@AfterTransaction@AfterTransaction indicates that the annotated void method should be run after a transaction is ended, for test
methods that have been configured to run within a transaction by using Spring’s @Transactional annotation.
@AfterTransaction methods are not required to be public and may be declared on Java 8-based interface default
methods.
@AfterTransaction 表示应在事务结束后运行被注释的 void 方法,对于通过使用 Spring 的 @Transactional 注解配置为在事务中运行测试方法。
@AfterTransaction 方法不需要是 public ,并且可以声明在基于 Java 8 的接口默认方法上。
1
Run this method after a transaction.
在事务后运行此方法。
1
Run this method after a transaction.
@Sql@Sql is used to annotate a test class or test method to configure SQL scripts to be run against a given database
during integration tests. The following example shows how to use it:
@Sql 用于注释测试类或测试方法,以配置在集成测试期间针对给定数据库运行的 SQL 脚本。以下示例展示了如何使用它:
1
Run two scripts for this test.
运行两个脚本进行此测试。
1
Run two scripts for this test.
See Executing SQL scripts declaratively with @Sql for further details.
查看使用 @Sql 以声明方式执行 SQL 脚本的详细信息。
@SqlConfig@SqlConfig defines metadata that is used to determine how to parse and run SQL scripts configured with the @Sql
annotation. The following example shows how to use it:
@SqlConfig 定义了用于确定如何解析和运行配置了 @Sql 注解的 SQL 脚本的元数据。以下示例展示了如何使用它:
1
Set the comment prefix and the separator in SQL scripts.
设置 SQL 脚本中的注释前缀和分隔符。
1
Set the comment prefix and the separator in SQL scripts.
@SqlMergeMode@SqlMergeMode is used to annotate a test class or test method to configure whether method-level @Sql declarations
are merged with class-level @Sql declarations. If @SqlMergeMode is not declared on a test class or test method, the
OVERRIDE merge mode will be used by default. With the OVERRIDE mode, method-level @Sql declarations will
effectively override class-level @Sql declarations.
@SqlMergeMode 用于注释测试类或测试方法,以配置方法级别的 @Sql 声明是否与类级别的 @Sql 声明合并。如果测试类或测试方法上未声明
@SqlMergeMode ,则默认使用 OVERRIDE 合并模式。在 OVERRIDE 模式下,方法级别的 @Sql 声明将有效地覆盖类级别的 @Sql
声明。
Note that a method-level @SqlMergeMode declaration overrides a class-level declaration.
请注意,方法级别的 @SqlMergeMode 声明会覆盖类级别的声明。
The following example shows how to use @SqlMergeMode at the class level.
以下示例展示了如何在类级别使用 @SqlMergeMode 。
1
Set the @Sql merge mode to MERGE for all test methods in the class.
将类中所有测试方法的 @Sql 合并模式设置为 MERGE 。
1
Set the @Sql merge mode to MERGE for all test methods in the class.
The following example shows how to use @SqlMergeMode at the method level.
以下示例展示了如何在方法级别使用 @SqlMergeMode 。
1
Set the @Sql merge mode to MERGE for a specific test method.
1
Set the @Sql merge mode to MERGE for a specific test method.
@SqlGroup@SqlGroup is a container annotation that aggregates several @Sql annotations. You can use @SqlGroup natively to
declare several nested @Sql annotations, or you can use it in conjunction with Java 8’s support for repeatable
annotations, where @Sql can be declared several times on the same class or method, implicitly generating this
container annotation. The following example shows how to declare an SQL group:
1
Declare a group of SQL scripts.
1
Declare a group of SQL scripts.
The following annotations are supported with standard semantics for all configurations of the Spring TestContext Framework. Note that these annotations are not specific to tests and can be used anywhere in the Spring Framework.
@Autowired
@Qualifier
@Value
@Resource (javax.annotation) if JSR-250 is present
@ManagedBean (javax.annotation) if JSR-250 is present
@Inject (javax.inject) if JSR-330 is present
@Named (javax.inject) if JSR-330 is present
@PersistenceContext (javax.persistence) if JPA is present
@PersistenceUnit (javax.persistence) if JPA is present
@Required
@Transactional (org.springframework.transaction.annotation)
with limited attribute support
JSR-250 Lifecycle Annotations
In the Spring TestContext Framework, you can use @PostConstruct and @PreDestroy with standard semantics on any
application components configured in the ApplicationContext. However, these lifecycle annotations have limited usage
within an actual test class.
If a method within a test class is annotated with @PostConstruct, that method runs before any before methods of the
underlying test framework (for example, methods annotated with JUnit Jupiter’s @BeforeEach), and that applies for
every test method in the test class. On the other hand, if a method within a test class is annotated with @PreDestroy,
that method never runs. Therefore, within a test class, we recommend that you use test lifecycle callbacks from the
underlying test framework instead of @PostConstruct and @PreDestroy.
The following annotations are supported only when used in conjunction with the SpringRunner, Spring’s JUnit 4 rules, or Spring’s JUnit 4 support classes:
@IfProfileValue@IfProfileValue indicates that the annotated test is enabled for a specific testing environment. If the configured
ProfileValueSource returns a matching value for the provided name, the test is enabled. Otherwise, the test is
disabled and, effectively, ignored.
You can apply @IfProfileValue at the class level, the method level, or both. Class-level usage of @IfProfileValue
takes precedence over method-level usage for any methods within that class or its subclasses. Specifically, a test is
enabled if it is enabled both at the class level and at the method level. The absence of @IfProfileValue means the
test is implicitly enabled. This is analogous to the semantics of JUnit 4’s @Ignore annotation, except that the
presence of @Ignore always disables a test.
The following example shows a test that has an @IfProfileValue annotation:
1
Run this test only when the Java vendor is "Oracle Corporation".
1
Run this test only when the Java vendor is "Oracle Corporation".
Alternatively, you can configure @IfProfileValue with a list of values (with OR semantics) to achieve TestNG-like
support for test groups in a JUnit 4 environment. Consider the following example:
1
Run this test for unit tests and integration tests.
1
Run this test for unit tests and integration tests.
@ProfileValueSourceConfiguration@ProfileValueSourceConfiguration is a class-level annotation that specifies what type of ProfileValueSource to use
when retrieving profile values configured through the @IfProfileValue annotation. If
@ProfileValueSourceConfiguration is not declared for a test, SystemProfileValueSource is used by default. The
following example shows how to use @ProfileValueSourceConfiguration:
@ProfileValueSourceConfiguration 是一个类级别的注解,用于指定在通过 @IfProfileValue 注解配置的配置文件值检索时使用哪种类型的
ProfileValueSource 。如果未为测试声明 @ProfileValueSourceConfiguration ,则默认使用 SystemProfileValueSource
。以下示例展示了如何使用 @ProfileValueSourceConfiguration :
1
Use a custom profile value source.
使用自定义配置文件值源。
1
Use a custom profile value source.
@Timed@Timed indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If
the text execution time exceeds the specified time period, the test fails.
@Timed 表示注解的测试方法必须在指定的时间段(以毫秒为单位)内完成执行。如果文本执行时间超过指定时间段,则测试失败。
The time period includes running the test method itself, any repetitions of the test (see @Repeat), as well as any
setting up or tearing down of the test fixture. The following example shows how to use it:
测试时间段包括运行测试方法本身、测试的任何重复(见 @Repeat ),以及测试装置的设置或拆除。以下示例展示了如何使用它:
1
Set the time period for the test to one second.
将测试的时间周期设置为 1 秒。
1
Set the time period for the test to one second.
Spring’s @Timed annotation has different semantics than JUnit 4’s @Test(timeout=…) support. Specifically, due to
the manner in which JUnit 4 handles test execution timeouts (that is, by executing the test method in a separate
Thread), @Test(timeout=…) preemptively fails the test if the test takes too long. Spring’s @Timed, on the other
hand, does not preemptively fail the test but rather waits for the test to complete before failing.
Spring 的 @Timed 注解与 JUnit 4 的 @Test(timeout=…) 支持具有不同的语义。具体来说,由于 JUnit 4 处理测试执行超时的方式(即在单独的
Thread 中执行测试方法),如果测试耗时过长, @Test(timeout=…) 会预先失败测试。另一方面,Spring 的 @Timed
不会预先失败测试,而是在测试完成后才失败。
@Repeat@Repeat indicates that the annotated test method must be run repeatedly. The number of times that the test method is
to be run is specified in the annotation.
@Repeat 表示标注的测试方法必须重复运行。测试方法需要运行的次数在注释中指定。
The scope of execution to be repeated includes execution of the test method itself as well as any setting up or tearing
down of the test fixture. When used with the SpringMethodRule, the scope additionally
includes preparation of the test instance by TestExecutionListener implementations. The following example shows how to
use the @Repeat annotation:
执行范围包括重复执行测试方法本身以及任何测试组件的设置或拆卸。当与 SpringMethodRule 一起使用时,执行范围还包括通过
TestExecutionListener 实现准备测试实例。以下示例展示了如何使用 @Repeat 注解:
1
Repeat this test ten times.
重复此测试十次。
1
Repeat this test ten times.
3.4.4. Spring JUnit Jupiter 测试注解
The following annotations are supported when used in conjunction with the
SpringExtension and JUnit Jupiter (that is, the programming model in JUnit
5):
以下注解在与 SpringExtension 和 JUnit Jupiter(即 JUnit 5 中的编程模型)一起使用时受支持:
@SpringJUnitConfig@SpringJUnitConfig is a composed annotation that combines @ExtendWith(SpringExtension.class) from JUnit Jupiter with
@ContextConfiguration from the Spring TestContext Framework. It can be used at the class level as a drop-in
replacement for @ContextConfiguration. With regard to configuration options, the only difference between
@ContextConfiguration and @SpringJUnitConfig is that component classes may be declared with the value attribute in
@SpringJUnitConfig.
@SpringJUnitConfig 是一个组合注解,它结合了来自 JUnit Jupiter 的 @ExtendWith(SpringExtension.class) 和来自 Spring
TestContext Framework 的 @ContextConfiguration 。它可以在类级别上作为 @ContextConfiguration 的直接替换使用。关于配置选项,
@ContextConfiguration 和 @SpringJUnitConfig 之间的唯一区别是,在 @SpringJUnitConfig 中可以使用 value 属性声明组件类。
The following example shows how to use the @SpringJUnitConfig annotation to specify a configuration class:
以下示例展示了如何使用 @SpringJUnitConfig 注解来指定配置类:
1
Specify the configuration class.
指定配置类。
1
Specify the configuration class.
The following example shows how to use the @SpringJUnitConfig annotation to specify the location of a configuration
file:
以下示例展示了如何使用 @SpringJUnitConfig 注解来指定配置文件的位置:
1
Specify the location of a configuration file.
指定配置文件的存放位置。
1
Specify the location of a configuration file.
See Context Management as well as the javadoc for
@SpringJUnitConfig
and @ContextConfiguration for further details.
查看上下文管理以及 @SpringJUnitConfig 和 @ContextConfiguration 的 javadoc 以获取更多详细信息。
@SpringJUnitWebConfig@SpringJUnitWebConfig is a composed annotation that combines @ExtendWith(SpringExtension.class) from JUnit Jupiter
with @ContextConfiguration and @WebAppConfiguration from the Spring TestContext Framework. You can use it at the
class level as a drop-in replacement for @ContextConfiguration and @WebAppConfiguration. With regard to
configuration options, the only difference between @ContextConfiguration and @SpringJUnitWebConfig is that you can
declare component classes by using the value attribute in @SpringJUnitWebConfig. In addition, you can override the
value attribute from @WebAppConfiguration only by using the resourcePath attribute in @SpringJUnitWebConfig.
@SpringJUnitWebConfig 是一个组合注解,它结合了 JUnit Jupiter 的 @ExtendWith(SpringExtension.class) 以及 Spring
TestContext Framework 的 @ContextConfiguration 和 @WebAppConfiguration 。您可以在类级别上使用它作为
@ContextConfiguration 和 @WebAppConfiguration 的替代品。关于配置选项, @ContextConfiguration 和
@SpringJUnitWebConfig 之间的唯一区别是您可以通过在 @SpringJUnitWebConfig 中使用 value 属性来声明组件类。此外,您只能通过在
@SpringJUnitWebConfig 中使用 resourcePath 属性来覆盖 @WebAppConfiguration 中的 value 属性。
The following example shows how to use the @SpringJUnitWebConfig annotation to specify a configuration class:
以下示例展示了如何使用 @SpringJUnitWebConfig 注解来指定配置类:
1
Specify the configuration class.
指定配置类。
1
Specify the configuration class.
The following example shows how to use the @SpringJUnitWebConfig annotation to specify the location of a configuration
file:
以下示例展示了如何使用 @SpringJUnitWebConfig 注解来指定配置文件的位置:
1
Specify the location of a configuration file.
指定配置文件的存放位置。
1
Specify the location of a configuration file.
@TestConstructor@TestConstructor is a type-level annotation that is used to configure how the parameters of a test class constructor
are autowired from components in the test’s ApplicationContext.
@TestConstructor 是一种类型级别的注解,用于配置测试类构造函数的参数如何从测试的 ApplicationContext 中的组件自动装配。
If @TestConstructor is not present or meta-present on a test class, the default test constructor autowire mode will
be used. See the tip below for details on how to change the default mode. Note, however, that a local declaration of
@Autowired on a constructor takes precedence over both @TestConstructor and the default mode.
如果测试类中没有 @TestConstructor 或存在元存在,将使用默认测试构造函数自动装配模式。有关如何更改默认模式的详细信息,请参阅下面的提示。请注意,构造函数上对
@Autowired 的局部声明优先于 @TestConstructor 和默认模式。
Changing the default test constructor autowire mode
更改默认测试构造函数自动装配模式
The default test constructor autowire mode can be changed by setting the spring.test.constructor.autowire.mode JVM
system property to all. Alternatively, the default mode may be set via the
SpringProperties
mechanism.
默认测试构造函数自动装配模式可以通过设置 spring.test.constructor.autowire.mode JVM 系统属性为 all 来更改。或者,也可以通过
SpringProperties 机制设置默认模式。
As of Spring Framework 5.3, the default mode may also be configured as
a JUnit Platform configuration parameter.
截至 Spring Framework 5.3,默认模式也可以配置为 JUnit 平台配置参数。
If the spring.test.constructor.autowire.mode property is not set, test class constructors will not be automatically
autowired.
如果未设置 spring.test.constructor.autowire.mode 属性,测试类构造函数将不会自动装配。
As of Spring Framework 5.2, @TestConstructor is only supported in conjunction with the SpringExtension for use with
JUnit Jupiter. Note that the SpringExtension is often automatically registered for you – for example, when using
annotations such as @SpringJUnitConfig and @SpringJUnitWebConfig or various test-related annotations from Spring
Boot Test.
截至 Spring Framework 5.2, @TestConstructor 仅与 SpringExtension 结合使用,用于与 JUnit Jupiter 一起使用。请注意,
SpringExtension 通常会自动为您注册 - 例如,当使用 @SpringJUnitConfig 和 @SpringJUnitWebConfig 或 Spring Boot Test
的各种测试相关注解时。
@NestedTestConfiguration@NestedTestConfiguration is a type-level annotation that is used to configure how Spring test configuration
annotations are processed within enclosing class hierarchies for inner test classes.
@NestedTestConfiguration 是一种类型级别的注解,用于配置在内部测试类中如何处理包围类层次结构中的 Spring 测试配置注解。
If @NestedTestConfiguration is not present or meta-present on a test class, in its supertype hierarchy, or in its
enclosing class hierarchy, the default enclosing configuration inheritance mode will be used. See the tip below for
details on how to change the default mode.
如果 @NestedTestConfiguration 在测试类中不存在或元存在,在其超类型层次结构中,或在其封装类层次结构中,将使用默认的封装配置继承模式。有关如何更改默认模式的详细信息,请参阅下面的提示。
Changing the default enclosing configuration inheritance mode
更改默认封装配置继承模式
The default enclosing configuration inheritance mode is INHERIT, but it can be changed by setting the
spring.test.enclosing.configuration JVM system property to OVERRIDE. Alternatively, the default mode may be set via
the
SpringProperties
mechanism.
默认的封装配置继承模式是 INHERIT ,但可以通过设置 spring.test.enclosing.configuration JVM 系统属性来更改 OVERRIDE
。或者,可以通过 SpringProperties 机制设置默认模式。
The Spring TestContext Framework honors @NestedTestConfiguration semantics for the following
annotations.
Spring TestContext 框架遵循以下注解的 @NestedTestConfiguration 语义。
The use of @NestedTestConfiguration typically only makes sense in conjunction with @Nested test classes in JUnit
Jupiter; however, there may be other testing frameworks with support for Spring and nested test classes that make use of
this annotation.
@NestedTestConfiguration 通常仅在 JUnit Jupiter 的 @Nested 测试类中使用才有意义;然而,可能存在其他支持 Spring
和嵌套测试类的测试框架,它们会使用这个注解。
See @Nested test class configuration for an example and
further details.
查看 @Nested 测试类配置示例及更多详细信息。
@EnabledIf@EnabledIf is used to signal that the annotated JUnit Jupiter test class or test method is enabled and should be run
if the supplied expression evaluates to true. Specifically, if the expression evaluates to Boolean.TRUE or a
String equal to true (ignoring case), the test is enabled. When applied at the class level, all test methods within
that class are automatically enabled by default as well.
@EnabledIf 用于表示已注解的 JUnit Jupiter 测试类或测试方法处于启用状态,并且如果提供的 expression 评估为 true
,则应该运行。具体来说,如果表达式评估为 Boolean.TRUE 或等于 true (忽略大小写)的 String
,则测试被启用。在类级别应用时,该类中的所有测试方法默认自动启用。
Expressions can be any of the following:
表达式可以是以下任何一种:
Spring Expression Language (
SpEL) expression. For example: @EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
春季表达式语言(SpEL)表达式。例如: @EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
Placeholder for a property available in the Spring
Environment. For
example: @EnabledIf("${smoke.tests.enabled}")
占位符,用于 Spring 中可用的属性 Environment 。例如: @EnabledIf("${smoke.tests.enabled}")
Text literal. For example: @EnabledIf("true")
文本字面。例如: @EnabledIf("true")
Note, however, that a text literal that is not the result of dynamic resolution of a property placeholder is of zero
practical value, since @EnabledIf("false") is equivalent to @Disabled and @EnabledIf("true") is logically
meaningless.
请注意,然而,一个不是属性占位符动态解析结果的文本字面量实际上毫无价值,因为 @EnabledIf("false") 等同于 @Disabled ,而
@EnabledIf("true") 在逻辑上没有意义。
You can use @EnabledIf as a meta-annotation to create custom composed annotations. For example, you can create a
custom @EnabledOnMac annotation as follows:
您可以使用 @EnabledIf 作为元注解来创建自定义组合注解。例如,您可以按照以下方式创建自定义 @EnabledOnMac 注解:
@EnabledOnMac is meant only as an example of what is possible. If you have that exact use case, please use the
built-in @EnabledOnOs(MAC) support in JUnit Jupiter.
@EnabledOnMac 仅作为可能性的示例。如果您有那个确切的使用场景,请使用 JUnit Jupiter 内置的 @EnabledOnOs(MAC) 支持。
Since JUnit 5.7, JUnit Jupiter also has a condition annotation named @EnabledIf. Thus, if you wish to use Spring’s
@EnabledIf support make sure you import the annotation type from the correct package.
自 JUnit 5.7 以来,JUnit Jupiter 也拥有一个名为 @EnabledIf 的条件注解。因此,如果您想使用 Spring 的 @EnabledIf
支持,请确保从正确的包中导入注解类型。
@DisabledIf@DisabledIf is used to signal that the annotated JUnit Jupiter test class or test method is disabled and should not be
run if the supplied expression evaluates to true. Specifically, if the expression evaluates to Boolean.TRUE or a
String equal to true (ignoring case), the test is disabled. When applied at the class level, all test methods within
that class are automatically disabled as well.
@DisabledIf 用于表示被注释的 JUnit Jupiter 测试类或测试方法被禁用,如果提供的 expression 评估为 true
则不应运行。具体来说,如果表达式评估为 Boolean.TRUE 或等于 true 的 String (忽略大小写),则测试被禁用。在类级别应用时,该类中的所有测试方法也会自动禁用。
Expressions can be any of the following:
表达式可以是以下任何一种:
Spring Expression Language (
SpEL) expression. For example: @DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
春季表达式语言(SpEL)表达式。例如: @DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
Placeholder for a property available in the Spring
Environment. For
example: @DisabledIf("${smoke.tests.disabled}")
占位符,用于 Spring 中可用的属性 Environment 。例如: @DisabledIf("${smoke.tests.disabled}")
Text literal. For example: @DisabledIf("true")
文本字面。例如: @DisabledIf("true")
Note, however, that a text literal that is not the result of dynamic resolution of a property placeholder is of zero
practical value, since @DisabledIf("true") is equivalent to @Disabled and @DisabledIf("false") is logically
meaningless.
请注意,然而,一个不是属性占位符动态解析结果的文本字面量实际上毫无价值,因为 @DisabledIf("true") 等同于 @Disabled ,而
@DisabledIf("false") 在逻辑上没有意义。
You can use @DisabledIf as a meta-annotation to create custom composed annotations. For example, you can create a
custom @DisabledOnMac annotation as follows:
您可以使用 @DisabledIf 作为元注解来创建自定义组合注解。例如,您可以按照以下方式创建自定义 @DisabledOnMac 注解:
@DisabledOnMac is meant only as an example of what is possible. If you have that exact use case, please use the
built-in @DisabledOnOs(MAC) support in JUnit Jupiter.
@DisabledOnMac 仅作为可能性的示例。如果您有那个确切的使用场景,请使用 JUnit Jupiter 内置的 @DisabledOnOs(MAC) 支持。
Since JUnit 5.7, JUnit Jupiter also has a condition annotation named @DisabledIf. Thus, if you wish to use Spring’s
@DisabledIf support make sure you import the annotation type from the correct package.
自 JUnit 5.7 以来,JUnit Jupiter 也拥有一个名为 @DisabledIf 的条件注解。因此,如果您想使用 Spring 的 @DisabledIf
支持,请确保从正确的包中导入注解类型。
3.4.5. 测试的元标注支持
You can use most test-related annotations
as meta-annotations
to create custom composed annotations and reduce configuration duplication across a test suite.
您可以使用大多数与测试相关的注释作为元注释来创建自定义组合注释,并减少测试套件中的配置重复。
You can use each of the following as a meta-annotation in conjunction with
the TestContext framework.
您可以将以下每个用作与 TestContext 框架结合使用的元注释。
@BootstrapWith
@ContextConfiguration
@ContextHierarchy
@ActiveProfiles
@TestPropertySource
@DirtiesContext
@WebAppConfiguration
@TestExecutionListeners
@Transactional
@BeforeTransaction
@AfterTransaction
@Commit
@Rollback
@Sql
@SqlConfig
@SqlMergeMode
@SqlGroup
@Repeat (only supported on JUnit 4)
@Repeat (仅支持 JUnit 4)
@Timed (only supported on JUnit 4)
@Timed (仅支持 JUnit 4)
@IfProfileValue (only supported on JUnit 4)
@IfProfileValue (仅支持 JUnit 4)
@ProfileValueSourceConfiguration (only supported on JUnit 4)
@ProfileValueSourceConfiguration (仅支持 JUnit 4)
@SpringJUnitConfig (only supported on JUnit Jupiter)
@SpringJUnitConfig (仅支持 JUnit Jupiter)
@SpringJUnitWebConfig (only supported on JUnit Jupiter)
@SpringJUnitWebConfig (仅支持 JUnit Jupiter)
@TestConstructor (only supported on JUnit Jupiter)
@TestConstructor (仅支持 JUnit Jupiter)
@NestedTestConfiguration (only supported on JUnit Jupiter)
@NestedTestConfiguration (仅支持 JUnit Jupiter)
@EnabledIf (only supported on JUnit Jupiter)
@EnabledIf (仅支持 JUnit Jupiter)
@DisabledIf (only supported on JUnit Jupiter)
@DisabledIf (仅支持 JUnit Jupiter)
Consider the following example:
考虑以下示例:
If we discover that we are repeating the preceding configuration across our JUnit 4-based test suite, we can reduce the
duplication by introducing a custom composed annotation that centralizes the common test configuration for Spring, as
follows:
如果我们发现我们在基于 JUnit 4 的测试套件中重复了前面的配置,我们可以通过引入一个自定义的复合注解来集中 Spring
的公共测试配置,从而减少重复,如下所示:
Then we can use our custom @TransactionalDevTestConfig annotation to simplify the configuration of individual JUnit 4
based test classes, as follows:
然后我们可以使用我们的自定义 @TransactionalDevTestConfig 注解来简化基于 JUnit 4 的测试类的配置,如下所示:
If we write tests that use JUnit Jupiter, we can reduce code duplication even further, since annotations in JUnit 5 can
also be used as meta-annotations. Consider the following example:
如果我们编写使用 JUnit Jupiter 的测试,我们还可以进一步减少代码重复,因为 JUnit 5 中的注解也可以用作元注解。考虑以下示例:
If we discover that we are repeating the preceding configuration across our JUnit Jupiter-based test suite, we can
reduce the duplication by introducing a custom composed annotation that centralizes the common test configuration for
Spring and JUnit Jupiter, as follows:
如果我们发现我们在基于 JUnit Jupiter 的测试套件中重复了前面的配置,我们可以通过引入一个自定义的复合注解来集中 Spring 和
JUnit Jupiter 的公共测试配置,从而减少重复,如下所示:
Then we can use our custom @TransactionalDevTestConfig annotation to simplify the configuration of individual JUnit
Jupiter based test classes, as follows:
然后我们可以使用我们的自定义 @TransactionalDevTestConfig 注解来简化基于 JUnit Jupiter 的测试类的配置,如下所示:
Since JUnit Jupiter supports the use of @Test, @RepeatedTest, ParameterizedTest, and others as meta-annotations,
you can also create custom composed annotations at the test method level. For example, if we wish to create a composed
annotation that combines the @Test and @Tag annotations from JUnit Jupiter with the @Transactional annotation from
Spring, we could create an @TransactionalIntegrationTest annotation, as follows:
由于 JUnit Jupiter 支持使用 @Test 、 @RepeatedTest 、 ParameterizedTest
等作为元注解,您也可以在测试方法级别创建自定义组合注解。例如,如果我们想创建一个组合注解,将 JUnit Jupiter 的 @Test 和
@Tag 注解与 Spring 的 @Transactional 注解结合起来,我们可以创建一个 @TransactionalIntegrationTest 注解,如下所示:
Then we can use our custom @TransactionalIntegrationTest annotation to simplify the configuration of individual JUnit
Jupiter based test methods, as follows:
然后我们可以使用我们的自定义 @TransactionalIntegrationTest 注解来简化基于 JUnit Jupiter 的各个测试方法的配置,如下所示: