Testing

Spring Boot 提供了许多实用工具和注释,以帮助测试你的应用程序.测试支持由两个模块提供: spring-boot-test 包含核心项目,而 spring-boot-test-autoconfigure 支持自动配置测试.

Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: spring-boot-test contains core items, and spring-boot-test-autoconfigure supports auto-configuration for tests.

大多数开发人员使用 spring-boot-starter-test “Starter”,它导入 Spring Boot 的两项测试模块以及 JUnit Jupiter、AssertJ、Hamcrest 以及许多其他有用的库.

Most developers use the spring-boot-starter-test “Starter”, which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries.

如果你具有使用 JUnit 4 的测试,则可以使用 JUnit 5 的 vintage 引擎来运行它们.若要使用 vintage 引擎,请添加对 junit-vintage-engine 的依赖,如下例所示:

If you have tests that use JUnit 4, JUnit 5’s vintage engine can be used to run them. To use the vintage engine, add a dependency on junit-vintage-engine, as shown in the following example:

<dependency>
	<groupId>org.junit.vintage</groupId>
	<artifactId>junit-vintage-engine</artifactId>
	<scope>test</scope>
	<exclusions>
		<exclusion>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-core</artifactId>
		</exclusion>
	</exclusions>
</dependency>

hamcrest-core`被排除在外,优先使用 `org.hamcrest:hamcrest,后者是 `spring-boot-starter-test`的一部分。

hamcrest-core is excluded in favor of org.hamcrest:hamcrest that is part of spring-boot-starter-test.

Test Scope Dependencies

spring-boot-starter-test “Starter”(在 test `scope`中)包含以下提供的库:

The spring-boot-starter-test “Starter” (in the test scope) contains the following provided libraries:

  • JUnit 5: The de-facto standard for unit testing Java applications.

  • {url-spring-framework-docs}/testing/integration.html[Spring Test] & Spring Boot Test: Utilities and integration test support for Spring Boot applications.

  • AssertJ: A fluent assertion library.

  • Hamcrest: A library of matcher objects (also known as constraints or predicates).

  • Mockito: A Java mocking framework.

  • JSONassert: An assertion library for JSON.

  • JsonPath: XPath for JSON.

  • Awaitility: A library for testing asynchronous systems.

我们通常会发现这些常见的库在写测试时很有用。如果这些库不适合您的需要,则可以添加您自己的额外的测试依赖项。

We generally find these common libraries to be useful when writing tests. If these libraries do not suit your needs, you can add additional test dependencies of your own.

Testing Spring Applications

依赖注入的一大优点在于它应该让您的代码更容易进行单元测试。您可以使用 `new`运算符实例化对象,而无需 Spring 参与。您还可以使用 _mock objects_代替实际依赖项。

One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the new operator without even involving Spring. You can also use mock objects instead of real dependencies.

通常,您需要超越单元测试,并开始集成测试(使用 Spring ApplicationContext)。能够在不需要部署您的应用程序或不需要连接到其他基础设施的情况下执行集成测试非常有用。

Often, you need to move beyond unit testing and start integration testing (with a Spring ApplicationContext). It is useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure.

Spring 框架包含一个专门用于此类集成测试的测试模块。您可以直接对 org.springframework:spring-test`声明一个依赖项,或使用 `spring-boot-starter-test "`Starter`"以传递方式引入它。

The Spring Framework includes a dedicated test module for such integration testing. You can declare a dependency directly to org.springframework:spring-test or use the spring-boot-starter-test “Starter” to pull it in transitively.

如果您之前没有使用过 `spring-test`模块,您应该首先阅读 Spring 框架参考文档中{url-spring-framework-docs}/testing.html[相关部分]。

If you have not used the spring-test module before, you should start by reading the {url-spring-framework-docs}/testing.html[relevant section] of the Spring Framework reference documentation.

Testing Spring Boot Applications

Spring Boot 应用程序是一个 Spring ApplicationContext,因此除了针对普通 Spring 上下文通常要做的工作之外,测试它不需要做任何特别的事情。

A Spring Boot application is a Spring ApplicationContext, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context.

Spring Boot 的外部属性、日志记录和其他功能只有在您使用 `SpringApplication`创建上下文时才会默认安装到上下文中。

External properties, logging, and other features of Spring Boot are installed in the context by default only if you use SpringApplication to create it.

Spring Boot 提供一个 @SpringBootTest`注释,当您需要 Spring Boot 功能时,它可以用作标准 `spring-test @ContextConfiguration`注释的替代项。注释通过 creating the `ApplicationContext used in your tests through SpringApplication起作用。除了 `@SpringBootTest`之外,还提供了一些其他注释以 testing more specific slices应用程序。

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication. In addition to @SpringBootTest a number of other annotations are also provided for testing more specific slices of an application.

如果您使用的是 JUnit 4,请不要忘记还将 @RunWith(SpringRunner.class)`添加到您的测试中,否则将忽略注释。如果您使用的是 JUnit 5,则无需添加等效的 `@ExtendWith(SpringExtension.class),因为 `@SpringBootTest`和其他 `@…​Test`注释已使用其做了注释。

If you are using JUnit 4, do not forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there is no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…​Test annotations are already annotated with it.

默认情况下,`@SpringBootTest`不会启动服务器。您可以使用 `@SpringBootTest`的 `webEnvironment`属性以进一步细化测试的运行方式:

By default, @SpringBootTest will not start a server. You can use the webEnvironment attribute of @SpringBootTest to further refine how your tests run:

  • MOCK(Default) : Loads a web ApplicationContext and provides a mock web environment. Embedded servers are not started when using this annotation. If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web ApplicationContext. It can be used in conjunction with @AutoConfigureMockMvc or @AutoConfigureWebTestClient for mock-based testing of your web application.

  • RANDOM_PORT: Loads a WebServerApplicationContext and provides a real web environment. Embedded servers are started and listen on a random port.

  • DEFINED_PORT: Loads a WebServerApplicationContext and provides a real web environment. Embedded servers are started and listen on a defined port (from your application.properties) or on the default port of 8080.

  • NONE: Loads an ApplicationContext by using SpringApplication but does not provide any web environment (mock or otherwise).

如果您的测试是 @Transactional,它默认会在每个测试方法的末尾回滚事务。但是,由于将此机制与 `RANDOM_PORT`或 `DEFINED_PORT`结合使用隐式地提供了一个真正的 Servlet 环境,因此 HTTP 客户端和服务器在单独的线程中运行,从而在单独的事务中运行。在这种情况下,在服务器上发起的任何事务都不会回滚。

If your test is @Transactional, it rolls back the transaction at the end of each test method by default. However, as using this arrangement with either RANDOM_PORT or DEFINED_PORT implicitly provides a real servlet environment, the HTTP client and server run in separate threads and, thus, in separate transactions. Any transaction initiated on the server does not roll back in this case.

`@SpringBootTest`与 `webEnvironment = WebEnvironment.RANDOM_PORT`还将在一个单独的随机端口上启动管理服务器,如果您的应用程序针对管理服务器使用某个不同的端口。

@SpringBootTest with webEnvironment = WebEnvironment.RANDOM_PORT will also start the management server on a separate random port if your application uses a different port for the management server.

Detecting Web Application Type

如果提供了 Spring MVC,则会配置基于常规 MVC 的应用程序上下文。如果您只有 Spring WebFlux,则我们会检测到这一点并改为配置基于 WebFlux 的应用程序上下文。

If Spring MVC is available, a regular MVC-based application context is configured. If you have only Spring WebFlux, we will detect that and configure a WebFlux-based application context instead.

如果两个都存在,则 Spring MVC 优先。如果您希望在此场景中测试响应式 Web 应用程序,则必须设置 configprop:spring.main.web-application-type[] 属性:

If both are present, Spring MVC takes precedence. If you want to test a reactive web application in this scenario, you must set the configprop:spring.main.web-application-type[] property:

Detecting Test Configuration

如果您熟悉 Spring 测试框架,则可能习惯使用 `@ContextConfiguration(classes=…​)`以指定要加载哪个 Spring 应用程序上下文。此外,您可能经常在测试中使用嵌套的 `@Configuration`类。

If you are familiar with the Spring Test Framework, you may be used to using @ContextConfiguration(classes=…​) in order to specify which Spring @Configuration to load. Alternatively, you might have often used nested @Configuration classes within your test.

在测试 Spring Boot 应用程序时,通常不需要这样做。Spring Boot 的 `@*Test`注释会在您没有明确定义一个注释时自动搜索您的主配置。

When testing Spring Boot applications, this is often not required. Spring Boot’s @*Test annotations search for your primary configuration automatically whenever you do not explicitly define one.

搜索算法从包含测试的包开始,一直往上查找,直到找到使用 `@SpringBootApplication`或 `@SpringBootConfiguration`进行注释的类。只要您以合理的方式进行 structured your code,通常能够找到您的主配置。

The search algorithm works up from the package that contains the test until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration. As long as you structured your code in a sensible way, your main configuration is usually found.

如果您使用了 test annotation to test a more specific slice of your application,则应该避免向 main method’s application class上特定区域添加配置设置。

If you use a test annotation to test a more specific slice of your application, you should avoid adding configuration settings that are specific to a particular area on the main method’s application class.

`@SpringBootApplication`的底层组件扫描配置定义了排除过滤器,这些过滤器用于确保分片工作按预期进行。如果您在 `@SpringBootApplication`注释类上使用明确的 `@ComponentScan`指令,请注意这些过滤器将被禁用。如果您正在使用分片,则应重新定义它们。

The underlying component scan configuration of @SpringBootApplication defines exclude filters that are used to make sure slicing works as expected. If you are using an explicit @ComponentScan directive on your @SpringBootApplication-annotated class, be aware that those filters will be disabled. If you are using slicing, you should define them again.

如果您想要自定义主配置,可以使用一个嵌套 `@TestConfiguration`类。与将用作应用程序主配置的嵌套 `@Configuration`类不同,嵌套的 `@TestConfiguration`类是作为应用程序主配置的补充使用的。

If you want to customize the primary configuration, you can use a nested @TestConfiguration class. Unlike a nested @Configuration class, which would be used instead of your application’s primary configuration, a nested @TestConfiguration class is used in addition to your application’s primary configuration.

Spring 的测试框架会缓存测试之间的应用程序上下文。因此,只要您的测试共享相同的配置(无论如何发现的),加载上下文的耗时过程只发生一次。

Spring’s test framework caches application contexts between tests. Therefore, as long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once.

Using the Test Configuration Main Method

通常,@SpringBootTest`发现的测试配置将是您的主 `@SpringBootApplication。在大多数结构良好的应用程序中,此配置类还将包含用于启动应用程序的 `main`方法。

Typically the test configuration discovered by @SpringBootTest will be your main @SpringBootApplication. In most well structured applications, this configuration class will also include the main method used to launch the application.

例如,以下代码模式对于典型的 Spring Boot 应用程序来说非常常见:

For example, the following is a very common code pattern for a typical Spring Boot application:

在上述示例中,main 方法除了委托给 SpringApplication.run 之外,不会执行任何其他操作.但是,在调用 SpringApplication.run 之前,可以通过更复杂的 main 方法来应用自定义设置.

In the example above, the main method doesn’t do anything other than delegate to SpringApplication.run. It is, however, possible to have a more complex main method that applies customizations before calling SpringApplication.run.

例如,以下是一个更改横幅模式并设置其他配置文件的应用程序:

For example, here is an application that changes the banner mode and sets additional profiles:

由于 main 方法中的自定义会影响由此产生的 ApplicationContext,所以您可能还想使用 main 方法来创建测试中使用的 ApplicationContext。默认情况下,@SpringBootTest 不会调用您的 main 方法,而是直接使用类本身来创建 ApplicationContext

Since customizations in the main method can affect the resulting ApplicationContext, it’s possible that you might also want to use the main method to create the ApplicationContext used in your tests. By default, @SpringBootTest will not call your main method, and instead the class itself is used directly to create the ApplicationContext

如果您想更改此行为,可以将 @SpringBootTestuseMainMethod 属性更改为 UseMainMethod.ALWAYSUseMainMethod.WHEN_AVAILABLE。如果将其设置为 ALWAYS,并且无法找到 main 方法,则测试将失败。如果将其设置为 WHEN_AVAILABLE,如果存在 main 方法,它将被使用;否则,将使用标准加载机制。

If you want to change this behavior, you can change the useMainMethod attribute of @SpringBootTest to UseMainMethod.ALWAYS or UseMainMethod.WHEN_AVAILABLE. When set to ALWAYS, the test will fail if no main method can be found. When set to WHEN_AVAILABLE the main method will be used if it is available, otherwise the standard loading mechanism will be used.

例如,以下测试将调用 MyApplicationmain 方法以创建 ApplicationContext。如果主方法设置另外的配置文件,则当 ApplicationContext 启动时它们将处于活动状态。

For example, the following test will invoke the main method of MyApplication in order to create the ApplicationContext. If the main method sets additional profiles then those will be active when the ApplicationContext starts.

Excluding Test Configuration

如果你的应用程序使用组件扫描(例如,如果你使用 @SpringBootApplication@ComponentScan),你可能会发现自己只为特定测试创建的顶级配置类意外地被到处选取。

If your application uses component scanning (for example, if you use @SpringBootApplication or @ComponentScan), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere.

正如我们have seen earlier@TestConfiguration 可以用于测试的内部类以自定义主配置。@TestConfiguration 也可以用于顶级类。这样表示该类不应通过扫描选取。然后,你可以在需要的地方显式导入该类,如下面的示例中所示:

As we have seen earlier, @TestConfiguration can be used on an inner class of a test to customize the primary configuration. @TestConfiguration can also be used on a top-level class. Doing so indicates that the class should not be picked up by scanning. You can then import the class explicitly where it is required, as shown in the following example:

如果你直接使用 @ComponentScan(即,不通过 @SpringBootApplication),则需要向其注册 TypeExcludeFilter。有关详细信息,请参阅 the Javadoc

If you directly use @ComponentScan (that is, not through @SpringBootApplication) you need to register the TypeExcludeFilter with it. See the Javadoc for details.

已导入的 @TestConfiguration 的处理时间比内部类 @TestConfiguration 早,已导入的 @TestConfiguration 的处理时间将比通过组件扫描找到的任何配置早。一般来说,这种排序差异没有明显的影响,但如果你依赖于 Bean 覆盖,则需要意识到这一点。

An imported @TestConfiguration is processed earlier than an inner-class @TestConfiguration and an imported @TestConfiguration will be processed before any configuration found through component scanning. Generally speaking, this difference in ordering has no noticeable effect but it is something to be aware of if you’re relying on bean overriding.

Using Application Arguments

如果您的应用程序期望 arguments,您可以使用 args 属性让 @SpringBootTest 注入它们。

If your application expects arguments, you can have @SpringBootTest inject them using the args attribute.

Testing With a Mock Environment

默认情况下,@SpringBootTest 不会启动服务器,而是为测试 Web 端点设置模拟环境。

By default, @SpringBootTest does not start the server but instead sets up a mock environment for testing web endpoints.

使用 Spring MVC,我们可以使用 {url-spring-framework-docs}/testing/spring-mvc-test-framework.html[MockMvc] 或 WebTestClient 查询我们的 Web 端点,如下例所示:

With Spring MVC, we can query our web endpoints using {url-spring-framework-docs}/testing/spring-mvc-test-framework.html[MockMvc] or WebTestClient, as shown in the following example:

如果您只想关注 Web 层而不想启动一个完整的 ApplicationContext,请考虑 using @WebMvcTest instead

If you want to focus only on the web layer and not start a complete ApplicationContext, consider using @WebMvcTest instead.

使用 Spring WebFlux 端点,您可以使用 {url-spring-framework-docs}/testing/webtestclient.html[WebTestClient],如下例所示:

With Spring WebFlux endpoints, you can use {url-spring-framework-docs}/testing/webtestclient.html[WebTestClient] as shown in the following example:

包括代码:MyMockWebTestClientTests[]

在模拟环境里进行测试通常比使用完整的 Servlet 容器运行测试更快。但是,由于模拟发生在 Spring MVC 层,因此依赖于较低级别 Servlet 容器行为的代码无法使用 MockMvc 直接进行测试。

Testing within a mocked environment is usually faster than running with a full servlet container. However, since mocking occurs at the Spring MVC layer, code that relies on lower-level servlet container behavior cannot be directly tested with MockMvc.

例如,Spring Boot 的错误处理基于 servlet 容器提供的 “error page” 支持。这意味着,虽然可以测试 MVC 层按预期抛出和处理异常,但无法直接测试是否渲染了特定的 custom error page。如果需要测试这些低层级问题,可以按照下一部分中所述启动一个完全运行的服务器。

For example, Spring Boot’s error handling is based on the “error page” support provided by the servlet container. This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific custom error page is rendered. If you need to test these lower-level concerns, you can start a fully running server as described in the next section.

Testing With a Running Server

如果需要启动一个完全运行的服务器,建议使用随机端口。如果使用 @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT),那么在每次运行测试时都会随机选择一个可用端口。

If you need to start a full running server, we recommend that you use random ports. If you use @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT), an available port is picked at random each time your test runs.

可以 inject the actual port used 到测试中,以使用 @LocalServerPort 批注。为了方便,需要对已启动的服务器进行 REST 调用的测试还可以 @Autowire 一个 {url-spring-framework-docs}/testing/webtestclient.html[WebTestClient],该注解解析到正在运行的服务器的相对链接,并提供了一个专门的 API 用于验证响应,如下例所示:

The @LocalServerPort annotation can be used to inject the actual port used into your test. For convenience, tests that need to make REST calls to the started server can additionally @Autowire a {url-spring-framework-docs}/testing/webtestclient.html[WebTestClient], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example:

在测试中使用 inject the actual port used 代码:MyRandomPortWebTestClientTests[]

WebTestClient 也可与 mock environment 结合使用,省去了使用运行服务器的必要性,方法是通过 @AutoConfigureWebTestClient 为测试类添加批注。

WebTestClient can also used with a mock environment, removing the need for a running server, by annotating your test class with @AutoConfigureWebTestClient.

此设置需要 spring-webflux 位于类路径上。如果无法或不愿添加 WebFlux,Spring Boot 还提供了一个 TestRestTemplate 工具:

This setup requires spring-webflux on the classpath. If you can not or will not add webflux, Spring Boot also provides a TestRestTemplate facility:

在测试中使用 TestRestTemplate 代码:MyRandomPortTestRestTemplateTests[]

Customizing WebTestClient

若要自定义 WebTestClient bean,请配置 WebTestClientBuilderCustomizer bean。此类任何 bean 都使用用于创建 WebTestClientWebTestClient.Builder 进行调用。

To customize the WebTestClient bean, configure a WebTestClientBuilderCustomizer bean. Any such beans are called with the WebTestClient.Builder that is used to create the WebTestClient.

Using JMX

由于测试上下文框架会缓存上下文,所以 JMX 默认被禁用,以防止相同组件注册在同一域上。如果此类测试需要访问 MBeanServer,请考虑也将其标记为脏:

As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain. If such test needs access to an MBeanServer, consider marking it dirty as well:

在测试中使用 MBeanServer 代码:MyJmxTests[]

Using Observations

如果为 a sliced test 添加 @AutoConfigureObservability 批注,它将自动配置一个 ObservationRegistry

If you annotate a sliced test with @AutoConfigureObservability, it auto-configures an ObservationRegistry.

Using Metrics

无论类路径是什么,使用 @SpringBootTest 时,仪表注册表(除了内存后备)都不会自动配置。

Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using @SpringBootTest.

如果需要在集成测试中将指标导出到不同后端,请对其添加 @AutoConfigureObservability 批注。

If you need to export metrics to a different backend as part of an integration test, annotate it with @AutoConfigureObservability.

如果为 a sliced test 添加 @AutoConfigureObservability 批注,它会自动配置一个内存 MeterRegistry。在分块测试中使用 @AutoConfigureObservability 批注进行数据导出不受支持。

If you annotate a sliced test with @AutoConfigureObservability, it auto-configures an in-memory MeterRegistry. Data exporting in sliced tests is not supported with the @AutoConfigureObservability annotation.

Using Tracing

无论您的类路径如何,在使用 `@SpringBootTest`时,报告数据的跟踪组件均不会自动配置。

Regardless of your classpath, tracing components which are reporting data are not auto-configured when using @SpringBootTest.

如果您需要那些组件作为集成测试的一部分,请使用 @AutoConfigureObservability 注释该测试。

If you need those components as part of an integration test, annotate the test with @AutoConfigureObservability.

如果您已创建了自定义报告组件(例如自定义 SpanExporterSpanHandler),并且您不希望它们在测试中处于活动状态,则可以使用 @ConditionalOnEnabledTracing 注释禁用它们。

If you have created your own reporting components (e.g. a custom SpanExporter or SpanHandler) and you don’t want them to be active in tests, you can use the @ConditionalOnEnabledTracing annotation to disable them.

如果您使用 @AutoConfigureObservability 注释 a sliced test ,它将自动配置无操作 Tracer 。使用 @AutoConfigureObservability 注释,在切片测试中不支持数据导出。

If you annotate a sliced test with @AutoConfigureObservability, it auto-configures a no-op Tracer. Data exporting in sliced tests is not supported with the @AutoConfigureObservability annotation.

Mocking and Spying Beans

在运行测试时,有时需要模拟应用程序上下文中特定组件。例如,在开发过程中可能无法使用某个远程服务的模式。当您想要模拟在真实的环境中可能难以触发的故障时,模拟也可能非常有用。

When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment.

Spring Boot 包含 @MockBean 注释,该注释可用于为 ApplicationContext 内的 Bean 定义一个 Mockito 模拟。可以使用此注释添加新 Bean 或替换现有的单一 Bean 定义。此注释可直接用于测试类、测试中的字段或 @Configuration 类和字段。当用在字段上时,也会注入创建的模拟实例。模拟 Bean 会在每次测试方法后自动重置。

Spring Boot includes a @MockBean annotation that can be used to define a Mockito mock for a bean inside your ApplicationContext. You can use the annotation to add new beans or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on @Configuration classes and fields. When used on a field, the instance of the created mock is also injected. Mock beans are automatically reset after each test method.

如果您的测试使用 Spring Boot 的任何测试注释(例如 @SpringBootTest),则此功能将自动启用。要将此功能与不同排列一起使用,必须明确添加侦听器,如下例所示:

If your test uses one of Spring Boot’s test annotations (such as @SpringBootTest), this feature is automatically enabled. To use this feature with a different arrangement, listeners must be explicitly added, as shown in the following example: include-code::listener/MyTests[]

以下示例使用模拟实现替换现有 RemoteService Bean:

The following example replaces an existing RemoteService bean with a mock implementation:

@MockBean 不能用于模拟在应用程序上下文刷新期间执行的 Bean 的行为。在执行测试时,应用程序上下文刷新已完成,并且配置模拟行为已为时已晚。我们建议在这种情况下使用 @Bean 方法创建和配置模拟。

@MockBean cannot be used to mock the behavior of a bean that is exercised during application context refresh. By the time the test is executed, the application context refresh has completed and it is too late to configure the mocked behavior. We recommend using a @Bean method to create and configure the mock in this situation.

此外,您还可以使用 @SpyBean 包装任何现有 Bean 使用 Mockito spy 。有关详细信息,请参阅 Javadoc

Additionally, you can use @SpyBean to wrap any existing bean with a Mockito spy. See the Javadoc for full details.

虽然 Spring 的测试框架在测试之间缓存应用程序上下文并为共享相同配置的测试重新使用一个上下文,但使用 @MockBean@SpyBean 会影响缓存密钥,这很可能会增加上下文的数量。

While Spring’s test framework caches application contexts between tests and reuses a context for tests sharing the same configuration, the use of @MockBean or @SpyBean influences the cache key, which will most likely increase the number of contexts.

如果您正在使用 @SpyBean 使用 @Cacheable 方法来监视 Bean,而该方法按名称引用参数,则必须使用 -parameters 编译您的应用程序。这可确保一旦 Bean 被监视,参数名称就可以供缓存基础设施使用。

If you are using @SpyBean to spy on a bean with @Cacheable methods that refer to parameters by name, your application must be compiled with -parameters. This ensures that the parameter names are available to the caching infrastructure once the bean has been spied upon.

当您使用 @SpyBean 监视由 Spring 代理的 Bean 时,在某些情况下您可能需要移除 Spring 的代理,例如使用 givenwhen 设置预期时。使用 AopTestUtils.getTargetObject(yourProxiedSpy) 进行移除。

When you are using @SpyBean to spy on a bean that is proxied by Spring, you may need to remove Spring’s proxy in some situations, for example when setting expectations using given or when. Use AopTestUtils.getTargetObject(yourProxiedSpy) to do so.

Auto-configured Tests

Spring Boot 的自动配置系统适用于应用程序,但有时对于测试来说可能会有点过分。它通常有助于仅加载测试应用程序的 “slice” 所需的配置部分。例如,您可能希望测试 Spring MVC 控制器是否正确映射了 URL,并且您不希望在这些测试中涉及数据库调用,或者您可能希望测试 JPA 实体,并且您在这些测试运行时不关心 Web 层。

Spring Boot’s auto-configuration system works well for applications but can sometimes be a little too much for tests. It often helps to load only the parts of the configuration that are required to test a “slice” of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you do not want to involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run.

spring-boot-test-autoconfigure 模块包含许多注释,可用于自动配置此类 “slices” 。它们每个的工作方式类似,提供加载 ApplicationContext 和一个或多个可用于自定义自动配置设置的 @AutoConfigure…​ 注释的 @…​Test 注释。

The spring-boot-test-autoconfigure module includes a number of annotations that can be used to automatically configure such “slices”. Each of them works in a similar way, providing a @…​Test annotation that loads the ApplicationContext and one or more @AutoConfigure…​ annotations that can be used to customize auto-configuration settings.

每个切片将组件扫描限制为适当的组件,并加载非常有限的一组自动配置类。如果您需要排除其中之一,大多数 @…​Test 注释提供一个 excludeAutoConfiguration 属性。或者,您可以使用 @ImportAutoConfiguration#exclude

Each slice restricts component scan to appropriate components and loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most @…​Test annotations provide an excludeAutoConfiguration attribute. Alternatively, you can use @ImportAutoConfiguration#exclude.

在一个测试中使用多个 “slices” 时,不支持使用多个 @…​Test 注解。如果您需要多个 “slices”,请选取一个 @…​Test 注解,并手动包含其他 “slices” 的 @AutoConfigure…​ 注解。

Including multiple “slices” by using several @…​Test annotations in one test is not supported. If you need multiple “slices”, pick one of the @…​Test annotations and include the @AutoConfigure…​ annotations of the other “slices” by hand.

还可以将 @AutoConfigure…​ 注解与标准 @SpringBootTest 注解一起使用。如果您对 “slicing” 应用程序不感兴趣,但希望得到部分自动配置的测试 bean,则可以使用此组合。

It is also possible to use the @AutoConfigure…​ annotations with the standard @SpringBootTest annotation. You can use this combination if you are not interested in “slicing” your application but you want some of the auto-configured test beans.

Auto-configured JSON Tests

使用 @JsonTest 注解测试对象 JSON 序列化和反序列化的工作是否符合预期。@JsonTest 自动配置可用的受支持 JSON 映射器,映射器可能是以下某个库:

To test that object JSON serialization and deserialization is working as expected, you can use the @JsonTest annotation. @JsonTest auto-configures the available supported JSON mapper, which can be one of the following libraries:

  • Jackson ObjectMapper, any @JsonComponent beans and any Jackson `Module`s

  • Gson

  • Jsonb

@JsonTest 启用的自动配置列表可以 found in the appendix

A list of the auto-configurations that are enabled by @JsonTest can be found in the appendix.

如果您需要配置自动配置的元素,可以使用 @AutoConfigureJsonTesters 注解。

If you need to configure elements of the auto-configuration, you can use the @AutoConfigureJsonTesters annotation.

Spring Boot 包含基于 AssertJ 的帮助器,可与 JSONAssert 和 JsonPath 库配合使用,以检查 JSON 是否符合预期。JacksonTesterGsonTesterJsonbTesterBasicJsonTester 类分别可用于 Jackson、Gson、Jsonb 和字符串。在使用 @JsonTest 时,测试类上的任何帮助器字段均可 @Autowired。以下示例显示 Jackson 的测试类:

Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath libraries to check that JSON appears as expected. The JacksonTester, GsonTester, JsonbTester, and BasicJsonTester classes can be used for Jackson, Gson, Jsonb, and Strings respectively. Any helper fields on the test class can be @Autowired when using @JsonTest. The following example shows a test class for Jackson:

JSON 帮助器类还可以在标准单元测试中直接使用。若要执行此操作,请在 @Before 方法中调用帮助器的 initFields 方法(如果您不使用 @JsonTest)。

JSON helper classes can also be used directly in standard unit tests. To do so, call the initFields method of the helper in your @Before method if you do not use @JsonTest.

如果您使用 Spring Boot 基于 AssertJ 的帮助器来断言给定 JSON 路径处的数值,则可能无法根据类型使用 isEqualTo。相反,您可以使用 AssertJ 的 satisfies 来断言该值符合给定的条件。例如,以下示例断言实际数字是一个浮点值,接近 0.15,偏移量在 0.01 之内。

If you use Spring Boot’s AssertJ-based helpers to assert on a number value at a given JSON path, you might not be able to use isEqualTo depending on the type. Instead, you can use AssertJ’s satisfies to assert that the value matches the given condition. For instance, the following example asserts that the actual number is a float value close to 0.15 within an offset of 0.01.

Auto-configured Spring MVC Tests

要测试 Spring MVC 控制器是否符合预期,请使用 @WebMvcTest 注解。@WebMvcTest 自动配置 Spring MVC 基础架构,并使扫描的 bean 仅限于 @Controller@ControllerAdvice@JsonComponentConverterGenericConverterFilterHandlerInterceptorWebMvcConfigurerWebMvcRegistrationsHandlerMethodArgumentResolver。使用 @WebMvcTest 注解时,不会扫描常规 @Component@ConfigurationProperties bean。可以使用 @EnableConfigurationProperties 来包含 @ConfigurationProperties bean。

To test whether Spring MVC controllers are working as expected, use the @WebMvcTest annotation. @WebMvcTest auto-configures the Spring MVC infrastructure and limits scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter, HandlerInterceptor, WebMvcConfigurer, WebMvcRegistrations, and HandlerMethodArgumentResolver. Regular @Component and @ConfigurationProperties beans are not scanned when the @WebMvcTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

可以 found in the appendix 启用 @WebMvcTest 的自动配置设置列表。

A list of the auto-configuration settings that are enabled by @WebMvcTest can be found in the appendix.

如果您需要注册其他组件,如 Jackson Module,则可以在测试中使用 @Import 来导入附加配置类。

If you need to register extra components, such as the Jackson Module, you can import additional configuration classes by using @Import on your test.

通常,@WebMvcTest 被限制到单个控制器,并与 @MockBean 结合使用,以便为必需的协作者提供模拟实现。

Often, @WebMvcTest is limited to a single controller and is used in combination with @MockBean to provide mock implementations for required collaborators.

@WebMvcTest 还自动配置 MockMvc。模拟 MVC 提供了一种快速测试 MVC 控制器的方法,而无需启动一个完整的 HTTP 服务器。

@WebMvcTest also auto-configures MockMvc. Mock MVC offers a powerful way to quickly test MVC controllers without needing to start a full HTTP server.

您还可以在非 @WebMvcTest (例如 @SpringBootTest)中使用 @AutoConfigureMockMvcMockMvc 进行自动配置。以下示例使用 MockMvc

You can also auto-configure MockMvc in a non-@WebMvcTest (such as @SpringBootTest) by annotating it with @AutoConfigureMockMvc. The following example uses MockMvc:

如果您需要配置自动配置的元素(例如,应应用哪些 servlet 过滤器),则可以在 @AutoConfigureMockMvc 注解中使用属性。

If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the @AutoConfigureMockMvc annotation.

如果您使用 HtmlUnit 和 Selenium,自动配置还提供了一个 HtmlUnit WebClient bean 和/或一个 Selenium WebDriver bean。以下示例使用 HtmlUnit:

If you use HtmlUnit and Selenium, auto-configuration also provides an HtmlUnit WebClient bean and/or a Selenium WebDriver bean. The following example uses HtmlUnit:

包含代码:MyHtmlUnitTests[]

默认情况下,Spring Boot 将 WebDriver bean 放入一个特殊的 “scope” 中,以确保在每个测试后驱动程序退出,并注入一个新实例。如果您不希望出现此行为,可以将 @Scope("singleton") 添加到 WebDriver @Bean 定义中。

By default, Spring Boot puts WebDriver beans in a special “scope” to ensure that the driver exits after each test and that a new instance is injected. If you do not want this behavior, you can add @Scope("singleton") to your WebDriver @Bean definition.

Spring Boot 创建的 webDriver 作用域将替换同名的任何用户定义作用域。如果您定义自己的 webDriver 作用域,可能会发现当使用 @WebMvcTest 时它停止工作。

The webDriver scope created by Spring Boot will replace any user defined scope of the same name. If you define your own webDriver scope you may find it stops working when you use @WebMvcTest.

如果类路径上有 Spring Security,@WebMvcTest 也将扫描 WebSecurityConfigurer bean。您可以使用 Spring Security 的测试支持,而不用为此类测试完全禁用安全。有关如何使用 Spring Security 的 MockMvc 支持的更多详细内容,请参阅此 Testing With Spring Security 指南部分。

If you have Spring Security on the classpath, @WebMvcTest will also scan WebSecurityConfigurer beans. Instead of disabling security completely for such tests, you can use Spring Security’s test support. More details on how to use Spring Security’s MockMvc support can be found in this Testing With Spring Security how-to section.

有时编写 Spring MVC 测试还不够;Spring Boot 可以帮助您运行 full end-to-end tests with an actual server

Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run full end-to-end tests with an actual server.

Auto-configured Spring WebFlux Tests

要测试 {url-spring-framework-docs}/web-reactive.html[Spring WebFlux] 控制器是否按预期工作,可以使用 @WebFluxTest 注解。@WebFluxTest 自动配置 Spring WebFlux 基础设施,并将扫描的 bean 限制为 @Controller@ControllerAdvice@JsonComponentConverterGenericConverterWebFilterWebFluxConfigurer。使用 @WebFluxTest 注解时,不会扫描常规 @Component@ConfigurationProperties bean。可以用 @EnableConfigurationProperties 包括 @ConfigurationProperties bean。

To test that {url-spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the @WebFluxTest annotation. @WebFluxTest auto-configures the Spring WebFlux infrastructure and limits scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, WebFilter, and WebFluxConfigurer. Regular @Component and @ConfigurationProperties beans are not scanned when the @WebFluxTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

可以通过 found in the appendix获取 @WebFluxTest 启用的自动配置列表。

A list of the auto-configurations that are enabled by @WebFluxTest can be found in the appendix.

如果您需要注册额外的组件,如 Jackson Module,可以在测试中使用 @Import 导入额外的配置类。

If you need to register extra components, such as Jackson Module, you can import additional configuration classes using @Import on your test.

通常,@WebFluxTest 局限于单个控制器,并与 @MockBean 注解结合使用,为所需的协作者提供模拟实现。

Often, @WebFluxTest is limited to a single controller and used in combination with the @MockBean annotation to provide mock implementations for required collaborators.

@WebFluxTest 还自动配置了 {url-spring-framework-docs}/testing/webtestclient.html[WebTestClient],它提供了一种强大的方式来快速测试 WebFlux 控制器,而无需启动完整的 HTTP 服务器。

@WebFluxTest also auto-configures {url-spring-framework-docs}/testing/webtestclient.html[WebTestClient], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server.

您还可以在非 @WebFluxTest (例如 @SpringBootTest)中通过使用 @AutoConfigureWebTestClient 对其进行注释来自动配置 WebTestClient。以下示例显示了一个同时使用 @WebFluxTestWebTestClient 的类:

You can also auto-configure WebTestClient in a non-@WebFluxTest (such as @SpringBootTest) by annotating it with @AutoConfigureWebTestClient. The following example shows a class that uses both @WebFluxTest and a WebTestClient:

此设置仅受 WebFlux 应用程序支持,因为在模拟 Web 应用程序中使用 WebTestClient 目前仅适用于 WebFlux。

This setup is only supported by WebFlux applications as using WebTestClient in a mocked web application only works with WebFlux at the moment.

@WebFluxTest 无法检测通过功能 Web 框架注册的路由。为了在上下文中测试 RouterFunction bean,请考虑使用 @Import@SpringBootTest 自行导入 RouterFunction

@WebFluxTest cannot detect routes registered through the functional web framework. For testing RouterFunction beans in the context, consider importing your RouterFunction yourself by using @Import or by using @SpringBootTest.

@WebFluxTest 无法检测到自定义安全配置已注册为类型为 SecurityWebFilterChain@Bean。要将其包括在测试中,您需要使用 @Import@SpringBootTest 导入注册了 bean 的配置。

@WebFluxTest cannot detect custom security configuration registered as a @Bean of type SecurityWebFilterChain. To include that in your test, you will need to import the configuration that registers the bean by using @Import or by using @SpringBootTest.

有时编写 Spring WebFlux 测试还不够;Spring Boot 可以帮助您运行 full end-to-end tests with an actual server

Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run full end-to-end tests with an actual server.

Auto-configured Spring GraphQL Tests

Spring GraphQL 提供了一个专门的测试支持模块;您需要将其添加到项目中:

Spring GraphQL offers a dedicated testing support module; you’ll need to add it to your project:

Maven
<dependencies>
	<dependency>
		<groupId>org.springframework.graphql</groupId>
		<artifactId>spring-graphql-test</artifactId>
		<scope>test</scope>
	</dependency>
	<!-- Unless already present in the compile scope -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-webflux</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>
Gradle
dependencies {
	testImplementation("org.springframework.graphql:spring-graphql-test")
	// Unless already present in the implementation configuration
	testImplementation("org.springframework.boot:spring-boot-starter-webflux")
}

此测试模块发送 {url-spring-graphql-docs}/#testing-graphqltester[GraphQlTester]。测试仪在测试中得到了广泛使用,因此务必熟悉它的使用。有 GraphQlTester 变体,Spring Boot 会根据测试类型自动配置它们:

This testing module ships the {url-spring-graphql-docs}/#testing-graphqltester[GraphQlTester]. The tester is heavily used in test, so be sure to become familiar with using it. There are GraphQlTester variants and Spring Boot will auto-configure them depending on the type of tests:

  • the ExecutionGraphQlServiceTester performs tests on the server side, without a client nor a transport

  • the HttpGraphQlTester performs tests with a client that connects to a server, with or without a live server

Spring Boot 可帮助您使用 @GraphQlTest 注释测试 {url-spring-graphql-docs}/#controllers[Spring GraphQL 控制器]。@GraphQlTest 自动配置 Spring GraphQL 基础架构,而不涉及任何传输或服务器。这将扫描的 bean 限制为 @ControllerRuntimeWiringConfigurerJsonComponentConverterGenericConverterDataFetcherExceptionResolverInstrumentationGraphQlSourceBuilderCustomizer。使用 @GraphQlTest 注释时,不会扫描常规 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 用于包含 @ConfigurationProperties bean。

Spring Boot helps you to test your {url-spring-graphql-docs}/#controllers[Spring GraphQL Controllers] with the @GraphQlTest annotation. @GraphQlTest auto-configures the Spring GraphQL infrastructure, without any transport nor server being involved. This limits scanned beans to @Controller, RuntimeWiringConfigurer, JsonComponent, Converter, GenericConverter, DataFetcherExceptionResolver, Instrumentation and GraphQlSourceBuilderCustomizer. Regular @Component and @ConfigurationProperties beans are not scanned when the @GraphQlTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

完整的自动配置列表可以通过 @GraphQlTest 启用。

A list of the auto-configurations that are enabled by @GraphQlTest can be found in the appendix.

通常,@GraphQlTest 仅限于一组控制器,并与 @MockBean 注释结合使用,以便为所需的协作者提供模拟实现。

Often, @GraphQlTest is limited to a set of controllers and used in combination with the @MockBean annotation to provide mock implementations for required collaborators.

::include-code::GreetingControllerTests[]

@SpringBootTest 测试是完全集成测试,涉及整个应用程序。在使用随机或定义的端口时,将会配置一个实时服务器,并且将自动提供 HttpGraphQlTester bean,以便您可以使用它来测试服务器。在配置了 MOCK 环境时,您还可以通过使用 @AutoConfigureHttpGraphQlTester 标注测试类,来请求 HttpGraphQlTester bean:

@SpringBootTest tests are full integration tests and involve the entire application. When using a random or defined port, a live server is configured and an HttpGraphQlTester bean is contributed automatically so you can use it to test your server. When a MOCK environment is configured, you can also request an HttpGraphQlTester bean by annotating your test class with @AutoConfigureHttpGraphQlTester:

::include-code::GraphQlIntegrationTests[]

Auto-configured Data Cassandra Tests

您可以使用 @DataCassandraTest 来测试 Cassandra 应用程序。默认情况下,它会配置 CassandraTemplate、扫描 @Table 类,并配置 Spring Data Cassandra 存储库。使用 @DataCassandraTest 注释时,不会扫描常规 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 用于包含 @ConfigurationProperties bean。(有关如何将 Cassandra 与 Spring Boot 搭配使用的更多信息,请参见 "Cassandra"。)

You can use @DataCassandraTest to test Cassandra applications. By default, it configures a CassandraTemplate, scans for @Table classes, and configures Spring Data Cassandra repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataCassandraTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using Cassandra with Spring Boot, see "Cassandra".)

完整的自动配置设置列表可以通过 @DataCassandraTest 启用。

A list of the auto-configuration settings that are enabled by @DataCassandraTest can be found in the appendix.

以下示例显示了在 Spring Boot 中使用 Cassandra 测试的典型设置:

The following example shows a typical setup for using Cassandra tests in Spring Boot:

::include-code::MyDataCassandraTests[]

Auto-configured Data Couchbase Tests

您可以使用 @DataCouchbaseTest 来测试 Couchbase 应用程序。默认情况下,它会配置 CouchbaseTemplateReactiveCouchbaseTemplate、扫描 @Document 类,并配置 Spring Data Couchbase 存储库。使用 @DataCouchbaseTest 注释时,不会扫描常规 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 用于包含 @ConfigurationProperties bean。(有关如何将 Couchbase 与 Spring Boot 搭配使用的更多信息,请参见本章前面的 "Couchbase"。)

You can use @DataCouchbaseTest to test Couchbase applications. By default, it configures a CouchbaseTemplate or ReactiveCouchbaseTemplate, scans for @Document classes, and configures Spring Data Couchbase repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataCouchbaseTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using Couchbase with Spring Boot, see "Couchbase", earlier in this chapter.)

完整的自动配置设置列表可以通过 @DataCouchbaseTest 启用。

A list of the auto-configuration settings that are enabled by @DataCouchbaseTest can be found in the appendix.

以下示例显示了在 Spring Boot 中使用 Couchbase 测试的典型设置:

The following example shows a typical setup for using Couchbase tests in Spring Boot:

::include-code::MyDataCouchbaseTests[]

Auto-configured Data Elasticsearch Tests

您可以使用 @DataElasticsearchTest 来测试 Elasticsearch 应用程序。默认情况下,它会配置 ElasticsearchRestTemplate、扫描 @Document 类,并配置 Spring Data Elasticsearch 存储库。使用 @DataElasticsearchTest 注释时,不会扫描常规 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 用于包含 @ConfigurationProperties bean。(有关如何将 Elasticsearch 与 Spring Boot 搭配使用的更多信息,请参见本章前面的 "Elasticsearch"。)

You can use @DataElasticsearchTest to test Elasticsearch applications. By default, it configures an ElasticsearchRestTemplate, scans for @Document classes, and configures Spring Data Elasticsearch repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataElasticsearchTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using Elasticsearch with Spring Boot, see "Elasticsearch", earlier in this chapter.)

完整的自动配置设置列表可以通过 @DataElasticsearchTest 启用。

A list of the auto-configuration settings that are enabled by @DataElasticsearchTest can be found in the appendix.

以下示例显示了在 Spring Boot 中使用 Elasticsearch 测试的典型设置:

The following example shows a typical setup for using Elasticsearch tests in Spring Boot:

::include-code::MyDataElasticsearchTests[]

Auto-configured Data JPA Tests

您可以使用`@DataJpaTest`注释来测试JPA应用程序。默认情况下,它扫描`@Entity`类和配置Spring Data JPA存储库。如果类路径中存在嵌入式数据库,它也会配置一个。通过将`spring.jpa.show-sql`属性设置为`true`,默认情况下会记录SQL查询。这可以使用注释的`showSql`属性禁用。

You can use the @DataJpaTest annotation to test JPA applications. By default, it scans for @Entity classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. SQL queries are logged by default by setting the spring.jpa.show-sql property to true. This can be disabled using the showSql attribute of the annotation.

使用`@DataJpaTest`注释时,不会扫描常规`@Component`和`@ConfigurationProperties`bean。@EnableConfigurationProperties`可用于包含@ConfigurationProperties`bean。

Regular @Component and @ConfigurationProperties beans are not scanned when the @DataJpaTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

由`@DataJpaTest`启用的自动配置设置的列表可以found in the appendix

A list of the auto-configuration settings that are enabled by @DataJpaTest can be found in the appendix.

默认情况下,data JPA测试是事务性的,并在每个测试结束时回滚。有关更多详细信息,请参阅Spring Framework参考文档中的{url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[相关章节]。如果不是您想要的内容,您可以按以下方式禁用测试或整个类的交易管理:

By default, data JPA tests are transactional and roll back at the end of each test. See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class as follows:

数据JPA测试也可能注入 {code-spring-boot-test-autoconfigure-src}/orm/jpa/TestEntityManager.java[TestEntityManager] bean,它提供了专为测试而设计的标准JPA`EntityManager`的替代方案。

Data JPA tests may also inject a {code-spring-boot-test-autoconfigure-src}/orm/jpa/TestEntityManager.java[TestEntityManager] bean, which provides an alternative to the standard JPA EntityManager that is specifically designed for tests.

还可以通过添加`@AutoConfigureTestEntityManager`将`TestEntityManager`自动配置到任何基于Spring的测试类。这样做时,请确保您的测试正在事务中运行,例如通过在您的测试类或方法上添加`@Transactional`。

TestEntityManager can also be auto-configured to any of your Spring-based test class by adding @AutoConfigureTestEntityManager. When doing so, make sure that your test is running in a transaction, for instance by adding @Transactional on your test class or method.

如果需要,还提供了一个`JdbcTemplate`。以下示例显示了正在使用的`@DataJpaTest`注释:

A JdbcTemplate is also available if you need that. The following example shows the @DataJpaTest annotation in use:

基于内存的嵌入式数据库通常适用于测试,因为它们速度快且无需安装。但是,如果您更愿意针对实际数据库运行测试,则可以使用`@AutoConfigureTestDatabase`注释,如以下示例所示:

In-memory embedded databases generally work well for tests, since they are fast and do not require any installation. If, however, you prefer to run tests against a real database you can use the @AutoConfigureTestDatabase annotation, as shown in the following example:

Auto-configured JDBC Tests

@JdbcTest`类似于@DataJpaTest`,但适用于仅需要`DataSource`的测试并且不使用Spring Data JDBC。默认情况下,它配置了一个内存中的嵌入式数据库和一个`JdbcTemplate`。使用`@JdbcTest`注释时,不会扫描常规`@Component`和`@ConfigurationProperties`bean。@EnableConfigurationProperties`可用于包含@ConfigurationProperties`bean。

@JdbcTest is similar to @DataJpaTest but is for tests that only require a DataSource and do not use Spring Data JDBC. By default, it configures an in-memory embedded database and a JdbcTemplate. Regular @Component and @ConfigurationProperties beans are not scanned when the @JdbcTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

由`@JdbcTest`启用的自动配置的列表可以found in the appendix

A list of the auto-configurations that are enabled by @JdbcTest can be found in the appendix.

默认情况下,JDBC测试是事务性的,并在每个测试结束时回滚。有关更多详细信息,请参阅Spring Framework参考文档中的{url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[相关章节]。如果不是您想要的内容,您可以按以下方式禁用测试或整个类的交易管理:

By default, JDBC tests are transactional and roll back at the end of each test. See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows:

如果您更喜欢让您的测试针对实际数据库运行,则可以使用`@AutoConfigureTestDatabase`注释,方法与`@DataJpaTest`相同。(请参见“Auto-configured Data JPA Tests”。)

If you prefer your test to run against a real database, you can use the @AutoConfigureTestDatabase annotation in the same way as for @DataJpaTest. (See "Auto-configured Data JPA Tests".)

Auto-configured Data JDBC Tests

@DataJdbcTest`类似于@JdbcTest`,但适用于使用Spring Data JDBC存储库的测试。默认情况下,它配置了一个基于内存的嵌入式数据库、JdbcTemplate`和Spring Data JDBC存储库。使用@DataJdbcTest`注释时,只扫描`AbstractJdbcConfiguration`子类,常规`@Component`和`@ConfigurationProperties`bean不被扫描。@EnableConfigurationProperties`可用于包含@ConfigurationProperties`bean。

@DataJdbcTest is similar to @JdbcTest but is for tests that use Spring Data JDBC repositories. By default, it configures an in-memory embedded database, a JdbcTemplate, and Spring Data JDBC repositories. Only AbstractJdbcConfiguration subclasses are scanned when the @DataJdbcTest annotation is used, regular @Component and @ConfigurationProperties beans are not scanned. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

由`@DataJdbcTest`启用的自动配置的列表可以found in the appendix

A list of the auto-configurations that are enabled by @DataJdbcTest can be found in the appendix.

默认情况下,Data JDBC测试是事务性的,并在每个测试结束时回滚。有关更多详细信息,请参阅Spring Framework参考文档中的{url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[相关章节]。如果不是您想要的内容,您可以为测试或整个测试类禁用事务管理,例如shown in the JDBC example

By default, Data JDBC tests are transactional and roll back at the end of each test. See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole test class as shown in the JDBC example.

如果您更喜欢让您的测试针对实际数据库运行,则可以使用`@AutoConfigureTestDatabase`注释,方法与`@DataJpaTest`相同。(请参见“Auto-configured Data JPA Tests”。)

If you prefer your test to run against a real database, you can use the @AutoConfigureTestDatabase annotation in the same way as for @DataJpaTest. (See "Auto-configured Data JPA Tests".)

Auto-configured Data R2DBC Tests

@DataR2dbcTest@DataJdbcTest 类似,但适用于使用 Spring Data R2DBC 存储库的测试。默认情况下,它会配置一个内存嵌入式数据库、一个 R2dbcEntityTemplate 和 Spring Data R2DBC 存储库。在使用 @DataR2dbcTest 注解时,不会扫描常规 @Component@ConfigurationProperties bean。可以使用 @EnableConfigurationProperties 来包括 @ConfigurationProperties bean。

@DataR2dbcTest is similar to @DataJdbcTest but is for tests that use Spring Data R2DBC repositories. By default, it configures an in-memory embedded database, an R2dbcEntityTemplate, and Spring Data R2DBC repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataR2dbcTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

可以通过 found in the appendix 查询由 @DataR2dbcTest 启用的自动配置列表。

A list of the auto-configurations that are enabled by @DataR2dbcTest can be found in the appendix.

默认情况下,Data R2DBC 测试是非事务性的。

By default, Data R2DBC tests are not transactional.

如果您更喜欢让您的测试针对实际数据库运行,则可以使用`@AutoConfigureTestDatabase`注释,方法与`@DataJpaTest`相同。(请参见“Auto-configured Data JPA Tests”。)

If you prefer your test to run against a real database, you can use the @AutoConfigureTestDatabase annotation in the same way as for @DataJpaTest. (See "Auto-configured Data JPA Tests".)

Auto-configured jOOQ Tests

你可以像使用 @JdbcTest 一样使用 @JooqTest,但适用于与 jOOQ 相关的测试。由于 jOOQ 严重依赖于与数据库架构相对应的基于 Java 的架构,因此使用了现有的 DataSource。如果你想在它替换为内存数据库,可以使用`@AutoConfigureTestDatabase`来覆盖那些设置。(有关在 Spring Boot 中使用 jOOQ 的更多信息,请参阅 "Using jOOQ")。在使用 @JooqTest 注解时,不会扫描常规 @Component@ConfigurationProperties bean。可以使用 @EnableConfigurationProperties 来包括 @ConfigurationProperties bean。

You can use @JooqTest in a similar fashion as @JdbcTest but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing DataSource is used. If you want to replace it with an in-memory database, you can use @AutoConfigureTestDatabase to override those settings. (For more about using jOOQ with Spring Boot, see "Using jOOQ".) Regular @Component and @ConfigurationProperties beans are not scanned when the @JooqTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

可以通过 found in the appendix 查询由 @JooqTest 启用的自动配置列表。

A list of the auto-configurations that are enabled by @JooqTest can be found in the appendix.

@JooqTest 配置了 DSLContext。以下示例展示了正在使用的 @JooqTest 注解:

@JooqTest configures a DSLContext. The following example shows the @JooqTest annotation in use:

默认情况下,JOOQ 测试是事务性的,并在每个测试结束时回滚。如果你不想要这样做,你可以禁用测试或整个测试类的事务管理,例如 shown in the JDBC example

JOOQ tests are transactional and roll back at the end of each test by default. If that is not what you want, you can disable transaction management for a test or for the whole test class as shown in the JDBC example.

Auto-configured Data MongoDB Tests

你可以使用 @DataMongoTest 来测试 MongoDB 应用程序。默认情况下,它会配置一个 MongoTemplate、扫描 @Document 类,并配置 Spring Data MongoDB 存储库。在使用 @DataMongoTest 注解时,不会扫描常规 @Component@ConfigurationProperties bean。可以使用 @EnableConfigurationProperties 来包括 @ConfigurationProperties bean。(有关在 Spring Boot 中使用 MongoDB 的更多信息,请参阅 "MongoDB")。

You can use @DataMongoTest to test MongoDB applications. By default, it configures a MongoTemplate, scans for @Document classes, and configures Spring Data MongoDB repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataMongoTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using MongoDB with Spring Boot, see "MongoDB".)

可以通过 found in the appendix 查询由 @DataMongoTest 启用的自动配置设置列表。

A list of the auto-configuration settings that are enabled by @DataMongoTest can be found in the appendix.

以下类示例展示了正在使用的 @DataMongoTest 注解:

The following class shows the @DataMongoTest annotation in use:

Auto-configured Data Neo4j Tests

你可以使用 @DataNeo4jTest 来测试 Neo4j 应用程序。默认情况下,它会扫描 @Node 类,并配置 Spring Data Neo4j 存储库。在使用 @DataNeo4jTest 注解时,不会扫描常规 @Component@ConfigurationProperties bean。可以使用 @EnableConfigurationProperties 来包括 @ConfigurationProperties bean。(有关在 Spring Boot 中使用 Neo4J 的更多信息,请参阅 "Neo4j")。

You can use @DataNeo4jTest to test Neo4j applications. By default, it scans for @Node classes, and configures Spring Data Neo4j repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataNeo4jTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using Neo4J with Spring Boot, see "Neo4j".)

可以通过 found in the appendix 查询由 @DataNeo4jTest 启用的自动配置设置列表。

A list of the auto-configuration settings that are enabled by @DataNeo4jTest can be found in the appendix.

以下示例展示了在 Spring Boot 中使用 Neo4J 测试的典型设置:

The following example shows a typical setup for using Neo4J tests in Spring Boot:

默认情况下,Data Neo4j 测试是事务性的,并在每个测试结束时回滚。有关更多详细信息,请参阅 Spring Framework 参考文档中的[相关部分](docs/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions)。如果你不想要这样做,你可以为某个测试或整个类禁用事务管理,如下所示:

By default, Data Neo4j tests are transactional and roll back at the end of each test. See the {url-spring-framework-docs}/testing/testcontext-framework/tx.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows:

不支持通过响应访问进行的事务测试。如果你使用这种样式,你必须如上所述配置 @DataNeo4jTest 测试。

Transactional tests are not supported with reactive access. If you are using this style, you must configure @DataNeo4jTest tests as described above.

Auto-configured Data Redis Tests

您可以使用 @DataRedisTest 来测试 Redis 应用程序。默认情况下,它会扫描 @RedisHash 课程和配置 Spring Data Redis 存储库。使用 @DataRedisTest 注释时,不会扫描常规的 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 可用于包含 @ConfigurationProperties bean。(有关将 Redis 与 Spring Boot 配合使用的更多信息,请参阅“Redis”。)

You can use @DataRedisTest to test Redis applications. By default, it scans for @RedisHash classes and configures Spring Data Redis repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataRedisTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using Redis with Spring Boot, see "Redis".)

可以通过 found in the appendix 列出由 @DataRedisTest 启用的自动配置设置。

A list of the auto-configuration settings that are enabled by @DataRedisTest can be found in the appendix.

以下示例演示了 @DataRedisTest 注释的使用方法:

The following example shows the @DataRedisTest annotation in use:

Auto-configured Data LDAP Tests

您可以使用 @DataLdapTest 来测试 LDAP 应用程序。默认情况下,它会配置内存中的嵌入式 LDAP(如果可用),配置一个 LdapTemplate,扫描 @Entry 课程和配置 Spring Data LDAP 存储库。使用 @DataLdapTest 注释时,不会扫描常规的 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 可用于包含 @ConfigurationProperties bean。(有关将 LDAP 与 Spring Boot 配合使用的更多信息,请参阅“LDAP”。)

You can use @DataLdapTest to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an LdapTemplate, scans for @Entry classes, and configures Spring Data LDAP repositories. Regular @Component and @ConfigurationProperties beans are not scanned when the @DataLdapTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans. (For more about using LDAP with Spring Boot, see "LDAP".)

可以通过 found in the appendix 列出由 @DataLdapTest 启用的自动配置设置。

A list of the auto-configuration settings that are enabled by @DataLdapTest can be found in the appendix.

以下示例演示了 @DataLdapTest 注释的使用方法:

The following example shows the @DataLdapTest annotation in use:

内存中的嵌入式 LDAP 通常适用于测试,因为它速度快且不需要任何开发人员安装。但是,如果您希望针对真正的 LDAP 服务器运行测试,则应该排除嵌入式 LDAP 自动配置,如下面的示例中所示:

In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example:

Auto-configured REST Clients

您可以使用 @RestClientTest 注释来测试 REST 客户端。默认情况下,它会自动配置 Jackson、GSON 和 Jsonb 支持,配置一个 RestTemplateBuilder 和一个 RestClient.Builder,并添加对 MockRestServiceServer 的支持。使用 @RestClientTest 注释时,不会扫描常规的 @Component@ConfigurationProperties bean。@EnableConfigurationProperties 可用于包含 @ConfigurationProperties bean。

You can use the @RestClientTest annotation to test REST clients. By default, it auto-configures Jackson, GSON, and Jsonb support, configures a RestTemplateBuilder and a RestClient.Builder, and adds support for MockRestServiceServer. Regular @Component and @ConfigurationProperties beans are not scanned when the @RestClientTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

可以通过 found in the appendix 列出由 @RestClientTest 启用的自动配置设置。

A list of the auto-configuration settings that are enabled by @RestClientTest can be found in the appendix.

您想要测试的特定 bean 应当使用 @RestClientTestvaluecomponents 属性进行指定。

The specific beans that you want to test should be specified by using the value or components attribute of @RestClientTest.

在被测 bean 中使用 RestTemplateBuilder 时,如果在构建 RestTemplate 时已调用 RestTemplateBuilder.rootUri(String rootUri),则应该从 MockRestServiceServer 预期中省略根 URI,如下面的示例所示:

When using a RestTemplateBuilder in the beans under test and RestTemplateBuilder.rootUri(String rootUri) has been called when building the RestTemplate, then the root URI should be omitted from the MockRestServiceServer expectations as shown in the following example:

在被测 bean 中使用 RestClient.Builder 时,或在不调用 rootUri(String rootURI) 的情况下使用 RestTemplateBuilder 时,必须在 MockRestServiceServer 预期中使用完整的 URI,如下面的示例所示:

When using a RestClient.Builder in the beans under test, or when using a RestTemplateBuilder without calling rootUri(String rootURI), the full URI must be used in the MockRestServiceServer expectations as shown in the following example:

Auto-configured Spring REST Docs Tests

可以使用 @AutoConfigureRestDocs 注释在测试中结合 Mock MVC、REST Assured 或 WebTestClient 使用 {url-spring-restdocs-site}[Spring REST Docs]。它无需在 Spring REST Docs 中使用 JUnit 扩展。

You can use the @AutoConfigureRestDocs annotation to use {url-spring-restdocs-site}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for the JUnit extension in Spring REST Docs.

可以使用 @AutoConfigureRestDocs 来覆盖默认输出目录(如果您使用的是 Maven,则为 target/generated-snippets;如果您使用的是 Gradle,则为 build/generated-snippets)。它还可用于配置显示在任何已记录 URI 中的主机、方案和端口。

@AutoConfigureRestDocs can be used to override the default output directory (target/generated-snippets if you are using Maven or build/generated-snippets if you are using Gradle). It can also be used to configure the host, scheme, and port that appears in any documented URIs.

Auto-configured Spring REST Docs Tests With Mock MVC

@AutoConfigureRestDocs 会自定义 MockMvc bean,以在对基于 servlet 的 web 应用程序进行测试时使用 Spring REST Docs。可以通过使用 @Autowired 注入该 bean,并且在测试中可以按平常使用 Mock MVC 和 Spring REST Docs 时的方式使用它,如下面的示例所示:

@AutoConfigureRestDocs customizes the MockMvc bean to use Spring REST Docs when testing servlet-based web applications. You can inject it by using @Autowired and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example:

在测试中使用 @AutoConfigureRestDocs 代码:MyUserDocumentationTests[]

如果需要对 Spring REST Docs 配置拥有比通过 @AutoConfigureRestDocs 的属性提供的更大的控制权,那么可以使用 RestDocsMockMvcConfigurationCustomizer bean,如下面的示例所示:

If you require more control over Spring REST Docs configuration than offered by the attributes of @AutoConfigureRestDocs, you can use a RestDocsMockMvcConfigurationCustomizer bean, as shown in the following example:

在测试中使用 RestDocsMockMvcConfigurationCustomizer 代码:MyRestDocsConfiguration[]

如果您希望利用 Spring REST Docs 对参数化输出目录的支持,则可以创建一个 RestDocumentationResultHandler bean。自动配置使用此结果处理程序调用 alwaysDo,从而导致每个 MockMvc 调用自动生成默认片段。以下示例显示了 RestDocumentationResultHandler 定义:

If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a RestDocumentationResultHandler bean. The auto-configuration calls alwaysDo with this result handler, thereby causing each MockMvc call to automatically generate the default snippets. The following example shows a RestDocumentationResultHandler being defined:

Auto-configured Spring REST Docs Tests With WebTestClient

在测试响应式 Web 应用程序时,@AutoConfigureRestDocs 还可以与 WebTestClient 一起使用。您可以使用 @Autowired 注入它,并在测试中使用它,就像在使用 @WebFluxTest 和 Spring REST Docs 时通常会做的那样,如下例所示:

@AutoConfigureRestDocs can also be used with WebTestClient when testing reactive web applications. You can inject it by using @Autowired and use it in your tests as you normally would when using @WebFluxTest and Spring REST Docs, as shown in the following example:

如果您需要对 @AutoConfigureRestDocs 的属性提供的 Spring REST Docs 配置进行更多控制,则可以使用 RestDocsWebTestClientConfigurationCustomizer bean,如下例所示:

If you require more control over Spring REST Docs configuration than offered by the attributes of @AutoConfigureRestDocs, you can use a RestDocsWebTestClientConfigurationCustomizer bean, as shown in the following example:

在测试中使用 RestDocsMockMvcConfigurationCustomizer 代码:MyRestDocsConfiguration[]

如果您希望利用 Spring REST Docs 对参数化输出目录的支持,则可以使用 WebTestClientBuilderCustomizer 为每个实体交换结果配置使用者。以下示例显示了此类 WebTestClientBuilderCustomizer 的定义:

If you want to make use of Spring REST Docs support for a parameterized output directory, you can use a WebTestClientBuilderCustomizer to configure a consumer for every entity exchange result. The following example shows such a WebTestClientBuilderCustomizer being defined:

Auto-configured Spring REST Docs Tests With REST Assured

@AutoConfigureRestDocs 使得预先配置为使用 Spring REST Docs 的 RequestSpecification bean 可用于您的测试。您可以使用 @Autowired 注入它,并在测试中使用它,就像在使用 REST Assured 和 Spring REST Docs 时通常会做的那样,如下例所示:

@AutoConfigureRestDocs makes a RequestSpecification bean, preconfigured to use Spring REST Docs, available to your tests. You can inject it by using @Autowired and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example:

在测试中使用 @AutoConfigureRestDocs 代码:MyUserDocumentationTests[]

如果您需要对 @AutoConfigureRestDocs 的属性提供的 Spring REST Docs 配置进行更多控制,则可以使用 RestDocsRestAssuredConfigurationCustomizer bean,如下例所示:

If you require more control over Spring REST Docs configuration than offered by the attributes of @AutoConfigureRestDocs, a RestDocsRestAssuredConfigurationCustomizer bean can be used, as shown in the following example:

在测试中使用 RestDocsMockMvcConfigurationCustomizer 代码:MyRestDocsConfiguration[]

Auto-configured Spring Web Services Tests

Auto-configured Spring Web Services Client Tests

您可以使用 @WebServiceClientTest 测试使用 Spring Web Services 项目调用 Web 服务的应用程序。默认情况下,它配置一个模拟 WebServiceServer bean 并自动自定义您的 WebServiceTemplateBuilder。(有关在 Spring Boot 中使用 Web 服务的更多信息,请参见 "Web Services"。)

You can use @WebServiceClientTest to test applications that call web services using the Spring Web Services project. By default, it configures a mock WebServiceServer bean and automatically customizes your WebServiceTemplateBuilder. (For more about using Web Services with Spring Boot, see "Web Services".)

可以 found in the appendix@WebServiceClientTest 启用的自动配置设置列表。

A list of the auto-configuration settings that are enabled by @WebServiceClientTest can be found in the appendix.

以下示例显示 @WebServiceClientTest 注释的使用情况:

The following example shows the @WebServiceClientTest annotation in use:

Auto-configured Spring Web Services Server Tests

您可以使用 @WebServiceServerTest 测试使用 Spring Web Services 项目实现 Web 服务的应用程序。默认情况下,它配置一个 MockWebServiceClient bean,该 bean 可用于调用您的 Web 服务端点。(有关在 Spring Boot 中使用 Web 服务的更多信息,请参见 "Web Services"。)

You can use @WebServiceServerTest to test applications that implement web services using the Spring Web Services project. By default, it configures a MockWebServiceClient bean that can be used to call your web service endpoints. (For more about using Web Services with Spring Boot, see "Web Services".)

可以 found in the appendix@WebServiceServerTest 启用的自动配置设置列表。

A list of the auto-configuration settings that are enabled by @WebServiceServerTest can be found in the appendix.

以下示例展示了 @WebServiceServerTest 注释的用法:

The following example shows the @WebServiceServerTest annotation in use:

Additional Auto-configuration and Slicing

每个 slice 都提供一个或多个 @AutoConfigure…​ 注释,主要定义作为 slice 一部分包含的自动配置。可以通过创建定制的 @AutoConfigure…​ 注释或在测试中添加 @ImportAutoConfiguration 来针对每个测试添加额外的自动配置,如下面的示例所示:

Each slice provides one or more @AutoConfigure…​ annotations that namely defines the auto-configurations that should be included as part of a slice. Additional auto-configurations can be added on a test-by-test basis by creating a custom @AutoConfigure…​ annotation or by adding @ImportAutoConfiguration to the test as shown in the following example:

务必不要使用常规 @Import 注释来导入自动配置,因为它们通过 Spring Boot 以特定方式进行处理。

Make sure to not use the regular @Import annotation to import auto-configurations as they are handled in a specific way by Spring Boot.

或者,可以通过将额外的自动配置注册到按 META-INF/spring 存储的文件中针对任何 slice 注释的使用添加这些配置,如下面的示例所示:

Alternatively, additional auto-configurations can be added for any use of a slice annotation by registering them in a file stored in META-INF/spring as shown in the following example:

META-INF/spring/org.springframework.boot.test.autoconfigure.jdbc.JdbcTest.imports
com.example.IntegrationAutoConfiguration

在此示例中,com.example.IntegrationAutoConfiguration 已在使用 @JdbcTest 注释的所有测试上启用。

In this example, the com.example.IntegrationAutoConfiguration is enabled on every test annotated with @JdbcTest.

您可以在此文件中使用注释加上 #

You can use comments with # in this file.

slice 或 @AutoConfigure…​ 注释可以以这种方式自定义,只要它使用 @ImportAutoConfiguration 元注释。

A slice or @AutoConfigure…​ annotation can be customized this way as long as it is meta-annotated with @ImportAutoConfiguration.

User Configuration and Slicing

如果您以合理的方式使用 structure your code,那么您的 @SpringBootApplication 类将作为测试配置使用 used by default

If you structure your code in a sensible way, your @SpringBootApplication class is used by default as the configuration of your tests.

因此,对应用程序主类重要的不是在其中散布特定的于其功能区域的设置配置。

It then becomes important not to litter the application’s main class with configuration settings that are specific to a particular area of its functionality.

假设您正在使用 Spring Data MongoDB,您依赖其自动配置,并且您已启用审核。您可以按如下方式定义您的 @SpringBootApplication

Assume that you are using Spring Data MongoDB, you rely on the auto-configuration for it, and you have enabled auditing. You could define your @SpringBootApplication as follows:

由于此类是测试的源配置,因此任何 slice 测试都会尝试实际启用 Mongo 审核,但这绝对不是您想执行的操作。建议的方法是将该特定区域的配置移到一个独立的 @Configuration 类中,该类与您的应用程序处在同一级别,如下面的示例所示:

Because this class is the source configuration for the test, any slice test actually tries to enable Mongo auditing, which is definitely not what you want to do. A recommended approach is to move that area-specific configuration to a separate @Configuration class at the same level as your application, as shown in the following example:

根据您的应用程序的复杂性,您可能拥有一个用于定制的单一的 @Configuration 类或每个域区域一个类。后者方法让您可以使用 @Import 注释在必要时在其中一个测试中启用它。有关您可能希望在什么时候对 slice 测试启用特定的 @Configuration 类,请参见 this how-to section

Depending on the complexity of your application, you may either have a single @Configuration class for your customizations or one class per domain area. The latter approach lets you enable it in one of your tests, if necessary, with the @Import annotation. See this how-to section for more details on when you might want to enable specific @Configuration classes for slice tests.

测试 slice 将 @Configuration 类排除在扫描之外。例如,对于 @WebMvcTest,以下配置将不会在由测试 slice 加载的应用程序上下文中包含给定的 WebMvcConfigurer bean:

Test slices exclude @Configuration classes from scanning. For example, for a @WebMvcTest, the following configuration will not include the given WebMvcConfigurer bean in the application context loaded by the test slice:

但是,以下配置将导致测试 slice 加载定制的 WebMvcConfigurer

The configuration below will, however, cause the custom WebMvcConfigurer to be loaded by the test slice.

混乱的另一个来源是类路径扫描。假设在以明智的方式构建代码时,需要扫描其他包。应用程序可能类似于以下代码:

Another source of confusion is classpath scanning. Assume that, while you structured your code in a sensible way, you need to scan an additional package. Your application may resemble the following code:

这样做实际上会覆盖默认组件扫描指令,其副作用是扫描这两个包,而不管你选择什么切片。例如,a`@DataJpaTest`似乎突然扫描了应用程序的组件和用户配置。同样,将自定义指令移到单独的类中是解决此问题的不错方法。

Doing so effectively overrides the default component scan directive with the side effect of scanning those two packages regardless of the slice that you chose. For instance, a @DataJpaTest seems to suddenly scan components and user configurations of your application. Again, moving the custom directive to a separate class is a good way to fix this issue.

如果这不是你的选择,则可以在测试层次结构的某个位置创建一个`@SpringBootConfiguration`,以便改用。或者,你可以为测试指定一个来源,以禁用查找默认来源的行为。

If this is not an option for you, you can create a @SpringBootConfiguration somewhere in the hierarchy of your test so that it is used instead. Alternatively, you can specify a source for your test, which disables the behavior of finding a default one.

Using Spock to Test Spring Boot Applications

Spock 2.2 or later can be used to test a Spring Boot application.To do so, add a dependency on a -groovy-4.0 version of Spock’s spock-spring module to your application’s build.spock-spring integrates Spring’s test framework into Spock.See the documentation for Spock’s Spring module for further details.

Spock 2.2 or later can be used to test a Spring Boot application. To do so, add a dependency on a -groovy-4.0 version of Spock’s spock-spring module to your application’s build. spock-spring integrates Spring’s test framework into Spock. See the documentation for Spock’s Spring module for further details.

Testcontainers

Testcontainers library provides a way to manage services running inside Docker containers.It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run.Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others.

The Testcontainers library provides a way to manage services running inside Docker containers. It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run. Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others.

Testcontainers can be used in a Spring Boot test as follows:

这将在运行任何测试之前启动运行 Neo4j 的 docker 容器(如果 Docker 在本地运行)。在大多数情况下,你需要配置应用程序以连接到容器中运行的服务。

This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run. In most cases, you will need to configure the application to connect to the service running in the container.

Service Connections

服务连接是到任何远程服务的连接。Spring Boot 的自动配置可以获取服务连接的详细信息,并使用它们来建立与远程服务的连接。执行此操作时,连接详细信息优先于任何与连接相关的配置属性。

A service connection is a connection to any remote service. Spring Boot’s auto-configuration can consume the details of a service connection and use them to establish a connection to a remote service. When doing so, the connection details take precedence over any connection-related configuration properties.

使用 Testcontainers 时,可以通过在测试类中注释容器字段为容器中运行的服务自动创建连接详细信息。

When using Testcontainers, connection details can be automatically created for a service running in a container by annotating the container field in the test class.

感谢`@ServiceConnection`,以上配置允许应用程序中的 Neo4j 相关 bean 与 Testcontainers 管理的 Docker 容器中运行的 Neo4j 通信。这是通过自动定义一个`Neo4jConnectionDetails`bean 来完成的,然后 Neo4j 自动配置使用该 bean,并覆盖任何与连接相关的配置属性。

Thanks to @ServiceConnection, the above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container. This is done by automatically defining a Neo4jConnectionDetails bean which is then used by the Neo4j auto-configuration, overriding any connection-related configuration properties.

你需要添加`spring-boot-testcontainers`module 作为测试依赖项,才能将服务连接与 Testcontainers 一起使用。

You’ll need to add the spring-boot-testcontainers module as a test dependency in order to use service connections with Testcontainers.

服务连接注释由注册为`spring.factories`的`ContainerConnectionDetailsFactory`类处理。`ContainerConnectionDetailsFactory`可以根据特定的`Container`子类或 Docker 映像名称创建一个`ConnectionDetails`bean。

Service connection annotations are processed by ContainerConnectionDetailsFactory classes registered with spring.factories. A ContainerConnectionDetailsFactory can create a ConnectionDetails bean based on a specific Container subclass, or the Docker image name.

以下服务连接工厂在中提供`spring-boot-testcontainers`jar:

The following service connection factories are provided in the spring-boot-testcontainers jar:

Connection Details Matched on

ActiveMQConnectionDetails

Containers named "symptoma/activemq" or ActiveMQContainer

ArtemisConnectionDetails

Containers of type ArtemisContainer

CassandraConnectionDetails

Containers of type CassandraContainer

CouchbaseConnectionDetails

Containers of type CouchbaseContainer

ElasticsearchConnectionDetails

Containers of type ElasticsearchContainer

FlywayConnectionDetails

Containers of type JdbcDatabaseContainer

JdbcConnectionDetails

Containers of type JdbcDatabaseContainer

KafkaConnectionDetails

Containers of type KafkaContainer or RedpandaContainer

LiquibaseConnectionDetails

Containers of type JdbcDatabaseContainer

MongoConnectionDetails

Containers of type MongoDBContainer

Neo4jConnectionDetails

Containers of type Neo4jContainer

OtlpMetricsConnectionDetails

Containers named "otel/opentelemetry-collector-contrib"

OtlpTracingConnectionDetails

Containers named "otel/opentelemetry-collector-contrib"

PulsarConnectionDetails

Containers of type PulsarContainer

R2dbcConnectionDetails

Containers of type MariaDBContainer, MSSQLServerContainer, MySQLContainer, OracleContainer, or PostgreSQLContainer

RabbitConnectionDetails

Containers of type RabbitMQContainer

RedisConnectionDetails

Containers named "redis"

ZipkinConnectionDetails

Containers named "openzipkin/zipkin"

默认情况下,将为给定的`Container`创建所有适用的连接详细信息 Bean。例如,PostgreSQLContainer`将同时创建`JdbcConnectionDetails`和`R2dbcConnectionDetails

By default all applicable connection details beans will be created for a given Container. For example, a PostgreSQLContainer will create both JdbcConnectionDetails and R2dbcConnectionDetails.

如果你只想创建适用的类型的子集,你可以使用`@ServiceConnection`的`type`属性。

If you want to create only a subset of the applicable types, you can use the type attribute of @ServiceConnection.

默认情况下,`Container.getDockerImageName()`用于获取用于查找连接详细信息的名称。只要 Spring Boot 能够获取`Container`的实例,这种方法就有效,就像在上面的示例中使用`static`字段一样。

By default Container.getDockerImageName() is used to obtain the name used to find connection details. This works as long as Spring Boot is able to get the instance of the Container, which is the case when using a static field like in the example above.

如果你正在使用`@Bean`方法,Spring Boot 将不会调用 Bean 方法来获取 Docker 镜像名称,因为这会导致急切初始化问题。相反,Bean 方法的返回类型用于找出应该使用哪个连接详细信息。只要你使用类型化的容器,例如`Neo4jContainer`或`RabbitMQContainer`,这种方法就有效。如果你使用`GenericContainer`,例如在 Redis 中使用,这种方法将停止工作,如下面的示例所示:

If you’re using a @Bean method, Spring Boot won’t call the bean method to get the Docker image name, because this would cause eager initialization issues. Instead, the return type of the bean method is used to find out which connection detail should be used. This works as long as you’re using typed containers, e.g. Neo4jContainer or RabbitMQContainer. This stops working if you’re using GenericContainer, e.g. with Redis, as shown in the following example:

Spring Boot 无法从`GenericContainer`中判断使用哪个容器镜像,因此必须使用`@ServiceConnection`中的`name`属性来提供该提示。

Spring Boot can’t tell from GenericContainer which container image is used, so the name attribute from @ServiceConnection must be used to provide that hint.

你还可以使用`@ServiceConnection`的`name`属性来覆盖将使用哪个连接详细信息,例如在使用自定义镜像时。如果你使用 Docker 镜像`registry.mycompany.com/mirror/myredis`,你将使用`@ServiceConnection(name="redis")来确保创建`RedisConnectionDetails

You can also use the name attribute of @ServiceConnection to override which connection detail will be used, for example when using custom images. If you are using the Docker image registry.mycompany.com/mirror/myredis, you’d use @ServiceConnection(name="redis") to ensure RedisConnectionDetails are created.

Dynamic Properties

略微冗长但也是更灵活的服务连接的替代方法是`@DynamicPropertySource`。一个静态`@DynamicPropertySource`方法允许将动态属性值添加到 Spring Environment。

A slightly more verbose but also more flexible alternative to service connections is @DynamicPropertySource. A static @DynamicPropertySource method allows adding dynamic property values to the Spring Environment.

上述配置允许应用程序中的 Neo4j 相关 Bean 与在 Testcontainers 管理的 Docker 容器中运行的 Neo4j 通信。

The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.

Test Utilities

在测试应用程序时通常有用的几个测试实用程序类打包在`spring-boot`中。

A few test utility classes that are generally useful when testing your application are packaged as part of spring-boot.

ConfigDataApplicationContextInitializer

ConfigDataApplicationContextInitializer`是一个`ApplicationContextInitializer,你可以将其应用于你的测试以加载 Spring Boot `application.properties`文件。当你不需要 `@SpringBootTest`提供的全部功能集时,可以使用它,如下面的示例所示:

ConfigDataApplicationContextInitializer is an ApplicationContextInitializer that you can apply to your tests to load Spring Boot application.properties files. You can use it when you do not need the full set of features provided by @SpringBootTest, as shown in the following example:

仅使用`ConfigDataApplicationContextInitializer`不提供对`@Value("${…​}")注入的支持。它的唯一作用是确保`application.properties`文件被加载到 Spring 的`Environment`中。对于@Value`支持,你需要另外配置一个`PropertySourcesPlaceholderConfigurer`或使用`@SpringBootTest`,它会自动为你配置一个。

Using ConfigDataApplicationContextInitializer alone does not provide support for @Value("${…​}") injection. Its only job is to ensure that application.properties files are loaded into Spring’s Environment. For @Value support, you need to either additionally configure a PropertySourcesPlaceholderConfigurer or use @SpringBootTest, which auto-configures one for you.

TestPropertyValues

TestPropertyValues`让你可以快速将属性添加到`ConfigurableEnvironment`或`ConfigurableApplicationContext。你可以用`key=value`字符串来调用它,如下所示:

TestPropertyValues lets you quickly add properties to a ConfigurableEnvironment or ConfigurableApplicationContext. You can call it with key=value strings, as follows:

OutputCapture

OutputCapture`是一个 JUnit `Extension,你可以用它来捕获`System.out`和`System.err`输出。要使用它,请添加`@ExtendWith(OutputCaptureExtension.class)`并将`CapturedOutput`注入到你的测试类构造函数或测试方法中,如下所示:

OutputCapture is a JUnit Extension that you can use to capture System.out and System.err output. To use it, add @ExtendWith(OutputCaptureExtension.class) and inject CapturedOutput as an argument to your test class constructor or test method as follows:

TestRestTemplate

`TestRestTemplate`是 Spring 的`RestTemplate`的一个方便的替代品,它在集成测试中很有用。你可以获得一个原生的模板或发送基本 HTTP 认证(包含用户名和密码)的模板。在这两种情况下,该模板都是容错的。这意味着它不会通过在 4xx 和 5xx 错误中抛出异常,以一种对测试友好的方式行事。相反,可以通过返回的`ResponseEntity`及其状态代码来检测到此类错误。

TestRestTemplate is a convenience alternative to Spring’s RestTemplate that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case, the template is fault tolerant. This means that it behaves in a test-friendly way by not throwing exceptions on 4xx and 5xx errors. Instead, such errors can be detected through the returned ResponseEntity and its status code.

Spring Framework 5.0 提供了一个新注解 WebTestClient,适用于 WebFlux integration testsWebFlux and MVC end-to-end testing。与 TestRestTemplate 不同,它为断言提供了流畅的 API。

Spring Framework 5.0 provides a new WebTestClient that works for WebFlux integration tests and both WebFlux and MVC end-to-end testing. It provides a fluent API for assertions, unlike TestRestTemplate.

建议使用 Apache HTTP 客户端(版本 5.1 或更高版本),但这并非强制性的。如果类路径中存在该客户端,则 TestRestTemplate 会通过相应地配置客户端做出响应。如果确实使用 Apache HTTP 客户端,则会启用一些额外的测试友好型功能:

It is recommended, but not mandatory, to use the Apache HTTP Client (version 5.1 or better). If you have that on your classpath, the TestRestTemplate responds by configuring the client appropriately. If you do use Apache’s HTTP client, some additional test-friendly features are enabled:

  • Redirects are not followed (so you can assert the response location).

  • Cookies are ignored (so the template is stateless).

TestRestTemplate 可以直接在你集成测试中实例化,如下面的示例所示:

TestRestTemplate can be instantiated directly in your integration tests, as shown in the following example:

或者,如果你在 WebEnvironment.RANDOM_PORTWebEnvironment.DEFINED_PORT 中使用 @SpringBootTest 注解,则可以注入一个完全配置的 TestRestTemplate 并开始使用它。如果需要,可以通过 RestTemplateBuilder Bean 应用其他自定义。任何未指定主机和端口的 URL 会自动连接到嵌入式服务器,如下面的示例所示:

Alternatively, if you use the @SpringBootTest annotation with WebEnvironment.RANDOM_PORT or WebEnvironment.DEFINED_PORT, you can inject a fully configured TestRestTemplate and start using it. If necessary, additional customizations can be applied through the RestTemplateBuilder bean. Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example: