Spring JUnit Jupiter Testing Annotations

SpringExtension 和 JUnit Jupiter(即 JUnit 5 中的编程模型)结合使用时,支持以下注释:

The following annotations are supported when used in conjunction with the SpringExtension and JUnit Jupiter (that is, the programming model in JUnit 5):

@SpringJUnitConfig

@SpringJUnitConfig 是一个组合注释,它将 JUnit Jupiter 中的 @ExtendWith(SpringExtension.class) 与 Spring TestContext Framework 中的 @ContextConfiguration 结合在一起。可以将其用在类级别,作为 @ContextConfiguration 的替代。关于配置选项,@ContextConfiguration@SpringJUnitConfig 之间的惟一区别是组件类可以使用 @SpringJUnitConfig 中的 `value `属性进行声明。

@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 注释指定配置类:

The following example shows how to use the @SpringJUnitConfig annotation to specify a configuration class:

Java
@SpringJUnitConfig(TestConfig.class) (1)
class ConfigurationClassJUnitJupiterSpringTests {
	// class body...
}
1 Specify the configuration class.
Kotlin
@SpringJUnitConfig(TestConfig::class) (1)
class ConfigurationClassJUnitJupiterSpringTests {
	// class body...
}
2 Specify the configuration class.

以下示例演示了如何使用 @SpringJUnitConfig 注释指定配置文件的位置:

The following example shows how to use the @SpringJUnitConfig annotation to specify the location of a configuration file:

Java
@SpringJUnitConfig(locations = "/test-config.xml") (1)
class XmlJUnitJupiterSpringTests {
	// class body...
}
1 Specify the location of a configuration file.
Kotlin
@SpringJUnitConfig(locations = ["/test-config.xml"]) (1)
class XmlJUnitJupiterSpringTests {
	// class body...
}
2 Specify the location of a configuration file.

请参阅 Context Management 以及https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit/jupiter/SpringJUnitConfig.html[@SpringJUnitConfig]和 @ContextConfiguration 的 javadoc 了解更多详情。

See Context Management as well as the javadoc for @SpringJUnitConfig and @ContextConfiguration for further details.

@SpringJUnitWebConfig

@SpringJUnitWebConfig 是一个组合注释,它将 JUnit Jupiter 中的 @ExtendWith(SpringExtension.class) 与 Spring TestContext Framework 中的 @ContextConfiguration@WebAppConfiguration 结合在一起。可以将其用在类级别,作为 @ContextConfiguration@WebAppConfiguration 的替代。关于配置选项,@ContextConfiguration@SpringJUnitWebConfig 之间的惟一区别是你可以使用 @SpringJUnitWebConfig 中的 value 属性来声明组件类。此外,只能使用 @SpringJUnitWebConfig 中的 resourcePath 属性来覆盖 @WebAppConfiguration 中的 value 属性。

@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 注释指定配置类:

The following example shows how to use the @SpringJUnitWebConfig annotation to specify a configuration class:

Java
@SpringJUnitWebConfig(TestConfig.class) (1)
class ConfigurationClassJUnitJupiterSpringWebTests {
	// class body...
}
1 Specify the configuration class.
Kotlin
@SpringJUnitWebConfig(TestConfig::class) (1)
class ConfigurationClassJUnitJupiterSpringWebTests {
	// class body...
}
2 Specify the configuration class.

以下示例演示了如何使用 @SpringJUnitWebConfig 注释指定配置文件的位置:

The following example shows how to use the @SpringJUnitWebConfig annotation to specify the location of a configuration file:

Java
@SpringJUnitWebConfig(locations = "/test-config.xml") (1)
class XmlJUnitJupiterSpringWebTests {
	// class body...
}
1 Specify the location of a configuration file.
Kotlin
@SpringJUnitWebConfig(locations = ["/test-config.xml"]) (1)
class XmlJUnitJupiterSpringWebTests {
	// class body...
}
2 Specify the location of a configuration file.

请参阅 Context Management 以及https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit/jupiter/web/SpringJUnitWebConfig.html[@SpringJUnitWebConfig]、https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/ContextConfiguration.html[@ContextConfiguration]和https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html[@WebAppConfiguration]的 javadoc 了解更多详情。

See Context Management as well as the javadoc for @SpringJUnitWebConfig, @ContextConfiguration, and @WebAppConfiguration for further details.

@TestConstructor

@TestConstructor 是一个注释,可以应用到测试类中,以配置如何自动装配测试类构造函数的参数,这些参数来自测试的 ApplicationContext 中的组件。

@TestConstructor is an annotation that can be applied to a test class to configure how the parameters of a test class constructor are autowired from components in the test’s ApplicationContext.

如果 @TestConstructor 没有出现在测试类或元出现,则将使用默认的 test constructor autowire mode。有关如何更改此默认模式的详细信息,请参阅下面的提示。但是,请注意,构造函数上的 @Autowired,@jakarta.inject.Inject, 或 @javax.inject.Inject 的局部声明优先于 @TestConstructor 和默认模式。

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, @jakarta.inject.Inject, or @javax.inject.Inject on a constructor takes precedence over both @TestConstructor and the default mode.

Changing the default test constructor autowire mode

可以通过将 spring.test.constructor.autowire.mode JVM 系统属性设置为 all 来更改默认 test constructor autowire mode。或者,可以通过 SpringProperties 机制设置默认模式。

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 框架 5.3 起,默认模式还可以配置为 JUnit Platform configuration parameter

As of Spring Framework 5.3, the default mode may also be configured as a JUnit Platform configuration parameter.

如果未设置 spring.test.constructor.autowire.mode 属性,将不会自动装配测试类构造函数。

If the spring.test.constructor.autowire.mode property is not set, test class constructors will not be automatically autowired.

从 Spring Framework 5.2 起,@TestConstructor 仅与 SpringExtension 结合使用,用于 JUnit Jupiter。请注意,SpringExtension 通常会为您自动注册——例如,在使用诸如 @SpringJUnitConfig@SpringJUnitWebConfig 或 Spring Boot Test 中的各种测试相关注释之类的注释时。

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.

@NestedTestConfiguration

@NestedTestConfiguration 是一种注释,可应用于测试类以配置在内部测试类的封闭类层次结构内如何处理 Spring 测试配置注释。

@NestedTestConfiguration is an annotation that can be applied to a test class to configure how Spring test configuration annotations are processed within enclosing class hierarchies for inner test classes.

如果 @NestedTestConfiguration 不存在或在其元数据中不存在于测试类中、其超类型层次结构中或其封闭类层次结构中,则将使用默认的 封闭配置继承模式。请参阅下面的提示,了解如何更改默认模式的详细信息。

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.

Changing the default enclosing configuration inheritance mode

默认 enclosing configuration inheritance modeINHERIT,但可以通过将 spring.test.enclosing.configuration JVM 系统属性设置为 OVERRIDE 来更改该模式。或者,可以通过 SpringProperties 机制设置默认模式。

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.

Spring TestContext Framework 遵循以下注解的 @NestedTestConfiguration 语义。

The Spring TestContext Framework honors @NestedTestConfiguration semantics for the following annotations.

使用 @NestedTestConfiguration 通常仅与 JUnit Jupiter 中的 @Nested 测试类结合才有意义;不过,可能还有其他测试框架支持 Spring 和嵌套测试类,这些框架会使用此注释。

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.

有关示例和进一步的详细信息,请参阅 xref:testing/testcontext-framework/support-classes.adoc#testcontext-junit-jupiter-nested-test-configuration[@Nested 测试类配置。

See @Nested test class configuration for an example and further details.

@EnabledIf

@EnabledIf 用于表示已注释的 JUnit Jupiter 测试类或测试方法已启用,并且如果提供的 expression 计算结果为 true,则应运行该类或方法。具体而言,如果表达式的计算结果为 Boolean.TRUE 或等于 trueString(忽略大小写),则测试将启用。在类级别应用时,该类中的所有测试方法在默认情况下也会自动启用。

@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.

表达式可以是以下任何一个:

Expressions can be any of the following:

  • Spring Expression Language (SpEL) expression. For example: @EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")

  • Placeholder for a property available in the Spring Environment. For example: @EnabledIf("${smoke.tests.enabled}")

  • Text literal. For example: @EnabledIf("true")

但请注意,不是动态解析属性占位符结果的文本文字没有实际价值,因为 @EnabledIf("false") 等同于 @Disabled,而 @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 用作元注释来创建自定的组合注释。例如,您可以按以下方式创建自定的 @EnabledOnMac 注释:

You can use @EnabledIf as a meta-annotation to create custom composed annotations. For example, you can create a custom @EnabledOnMac annotation as follows:

  • Java

  • Kotlin

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@EnabledIf(
	expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
	reason = "Enabled on Mac OS"
)
public @interface EnabledOnMac {}
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@EnabledIf(
		expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
		reason = "Enabled on Mac OS"
)
annotation class EnabledOnMac {}

@EnabledOnMac 只是作为可以执行的操作的示例。如果您有确切的用例,请使用 JUnit Jupiter 中内置的 @EnabledOnOs(MAC) 支持。

@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.

自 JUnit 5.7 以来,JUnit Jupiter 还具有名为 @EnabledIf 的条件注释。因此,如果您希望使用 Spring 的 @EnabledIf 支持,请确保从正确的包中导入注释类型。

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.

@DisabledIf

@DisabledIf 用于表示已注释的 JUnit Jupiter 测试类或测试方法已禁用,并且如果提供的 expression 计算结果为 true,则不应运行该类或方法。具体而言,如果表达式的计算结果为 Boolean.TRUE 或等于 trueString(忽略大小写),则测试将禁用。在类级别应用时,该类中的所有测试方法在默认情况下也会自动禁用。

@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.

表达式可以是以下任何一个:

Expressions can be any of the following:

  • Spring Expression Language (SpEL) expression. For example: @DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")

  • Placeholder for a property available in the Spring Environment. For example: @DisabledIf("${smoke.tests.disabled}")

  • Text literal. For example: @DisabledIf("true")

但请注意,不是动态解析属性占位符结果的文本文字没有实际价值,因为 @DisabledIf("true") 等同于 @Disabled,而 @DisabledIf("false") 在逻辑上没有意义。

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 用作元注释来创建自定的组合注释。例如,您可以按以下方式创建自定的 @DisabledOnMac 注释:

You can use @DisabledIf as a meta-annotation to create custom composed annotations. For example, you can create a custom @DisabledOnMac annotation as follows:

  • Java

  • Kotlin

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@DisabledIf(
	expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
	reason = "Disabled on Mac OS"
)
public @interface DisabledOnMac {}
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@DisabledIf(
		expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
		reason = "Disabled on Mac OS"
)
annotation class DisabledOnMac {}

@DisabledOnMac 只是作为可以执行的操作的示例。如果您有确切的用例,请使用 JUnit Jupiter 中内置的 @DisabledOnOs(MAC) 支持。

@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.

自 JUnit 5.7 以来,JUnit Jupiter 还具有名为 @DisabledIf 的条件注释。因此,如果您希望使用 Spring 的 @DisabledIf 支持,请确保从正确的包中导入注释类型。

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.