此版本仍在开发中,尚未稳定。如需最新的稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

RestTestClient

RestTestClient 是一个为测试服务器应用程序设计的HTTP客户端。它封装了 Spring的RestClient并使用它来执行请求, 但提供了一个用于验证响应的测试外观。RestTestClient可用于 执行端到端的HTTP测试。它也可以用来测试Spring MVC 应用程序,无需运行服务器,通过MockMvc实现。spring-doc.cadn.net.cn

安装

要设置一个RestTestClient,您需要选择一个服务器配置进行绑定。这可以是多个MockMvc配置选择之一,或是连接到一个实时服务器。spring-doc.cadn.net.cn

绑定到控制器

此设置允许你通过模拟请求和响应对象来测试特定的控制器, 而无需运行服务器。spring-doc.cadn.net.cn

RestTestClient client =
		RestTestClient.bindToController(new TestController()).build();
val client = RestTestClient.bindToController(TestController()).build()

绑定到ApplicationContext

此配置使您能够在没有运行服务器的情况下,使用Spring MVC基础设施和控制器声明加载Spring配置,并通过模拟请求和响应对象来处理请求。spring-doc.cadn.net.cn

import org.junit.jupiter.api.BeforeEach;

import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.web.servlet.client.RestTestClient;
import org.springframework.web.context.WebApplicationContext;


@SpringJUnitConfig(WebConfig.class) // Specify the configuration to load
public class RestClientContextTests {

	RestTestClient client;

	@BeforeEach
	void setUp(WebApplicationContext context) {  // Inject the configuration
		// Create the `RestTestClient`
		client = RestTestClient.bindToApplicationContext(context).build();
	}

}
import org.junit.jupiter.api.BeforeEach
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig
import org.springframework.test.web.servlet.client.RestTestClient
import org.springframework.web.context.WebApplicationContext

@SpringJUnitConfig(WebConfig::class) // Specify the configuration to load
class RestClientContextTests {

	lateinit var client: RestTestClient

	@BeforeEach
	fun setUp(context: WebApplicationContext) {  // Inject the configuration
		// Create the `RestTestClient`
		client = RestTestClient.bindToApplicationContext(context).build()
	}
}

绑定到路由函数

此设置允许您通过模拟请求和响应对象测试 功能端点,而无需运行服务器。spring-doc.cadn.net.cn

RouterFunction<?> route = ...
client = RestTestClient.bindToRouterFunction(route).build();
val route: RouterFunction<*> = ...
val client = RestTestClient.bindToRouterFunction(route).build()

绑定到服务器

此设置连接到运行中的服务器以执行完整的端到端HTTP测试:spring-doc.cadn.net.cn

client = RestTestClient.bindToServer().baseUrl("http://localhost:8080").build();
client = RestTestClient.bindToServer().baseUrl("http://localhost:8080").build()

客户端配置

除了前面提到的服务器设置选项,您还可以配置客户端选项,包括基础URL、默认头、客户端过滤器等。这些选项在初始的bindTo调用后即可方便地进行配置,如下所示:spring-doc.cadn.net.cn

client = RestTestClient.bindToController(new TestController())
		.baseUrl("/test")
		.build();
client = RestTestClient.bindToController(TestController())
		.baseUrl("/test")
		.build()

编写测试

RestClientRestTestClient 在调用 exchange() 之前具有相同的API。之后,RestTestClient 提供了两种验证响应的替代方法:spring-doc.cadn.net.cn

  1. 内置断言通过一系列期望扩展了请求工作流程spring-doc.cadn.net.cn

  2. AssertJ 集成 通过 assertThat() 语句验证响应spring-doc.cadn.net.cn

内置断言

要使用内置的断言,请在调用exchange()后保持在工作流中,并使用其中一个期望方法。例如:spring-doc.cadn.net.cn

client.get().uri("/persons/1")
		.accept(MediaType.APPLICATION_JSON)
		.exchange()
		.expectStatus().isOk()
		.expectHeader().contentType(MediaType.APPLICATION_JSON)
		.expectBody();
client.get().uri("/persons/1")
	.accept(MediaType.APPLICATION_JSON)
	.exchange()
	.expectStatus().isOk()
	.expectHeader().contentType(MediaType.APPLICATION_JSON)
	.expectBody()

如果您希望即使其中一个断言失败,所有断言都得到执行,可以使用 expectAll(..) 而不是多个链式调用的 expect*(..)。此功能类似于 AssertJ 中的 软断言 支持以及 JUnit Jupiter 中的 assertAll() 支持。spring-doc.cadn.net.cn

client.get().uri("/persons/1")
		.accept(MediaType.APPLICATION_JSON)
		.exchange()
		.expectAll(
				spec -> spec.expectStatus().isOk(),
				spec -> spec.expectHeader().contentType(MediaType.APPLICATION_JSON)
		);
client.get().uri("/persons/1")
	.accept(MediaType.APPLICATION_JSON)
	.exchange()
	.expectAll(
		{ spec -> spec.expectStatus().isOk() },
		{ spec -> spec.expectHeader().contentType(MediaType.APPLICATION_JSON) }
	)

然后你可以选择通过以下方式对响应体进行解码:spring-doc.cadn.net.cn

如果内置的断言不够用,你可以直接使用该对象并执行任何其他断言:spring-doc.cadn.net.cn

client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody(Person.class)
		.consumeWith(result -> {
			// custom assertions (for example, AssertJ)...
		});
client.get().uri("/persons/1")
	.exchange()
	.expectStatus().isOk()
	.expectBody<Person>()
	.consumeWith {
		// custom assertions (for example, AssertJ)...
	}

或者,您可以退出工作流程并获得代码EntityExchangeResultspring-doc.cadn.net.cn

EntityExchangeResult<Person> result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody(Person.class)
		.returnResult();

Person person = result.getResponseBody();
HttpHeaders requestHeaders = result.getRequestHeaders();
val result = client.get().uri("/persons/1")
	.exchange()
	.expectStatus().isOk
	.expectBody<Person>()
	.returnResult()

val person: Person? = result.responseBody
val requestHeaders = result.responseHeaders
当你需要解码到具有泛型的目标类型时,查找接受 ParameterizedTypeReference 而不是 Class<T> 的重载方法。

没有内容

如果响应预期不包含内容,可以按以下方式断言:spring-doc.cadn.net.cn

client.post().uri("/persons")
		.body(person)
		.exchange()
		.expectStatus().isCreated()
		.expectBody().isEmpty();
client.post().uri("/persons")
	.body(person)
	.exchange()
	.expectStatus().isCreated()
	.expectBody().isEmpty()

如果你想忽略响应内容,以下方式会释放内容而没有任何断言:spring-doc.cadn.net.cn

client.post().uri("/persons")
		.body(person)
		.exchange()
		.expectStatus().isCreated()
		.expectBody(Void.class);
client.get().uri("/persons/123")
	.exchange()
	.expectStatus().isNotFound
	.expectBody<Unit>()
消费响应体(例如,使用expectBody)是必需的,如果你的测试正在使用 对池化缓冲区的泄漏检测。没有这个操作,工具将报告缓冲区存在泄漏。

JSON 内容

您可以使用 expectBody() 而不指定目标类型,以对原始内容进行断言,而不是通过高级对象进行。spring-doc.cadn.net.cn

要使用 JSONAssert 验证完整的 JSON 内容:spring-doc.cadn.net.cn

client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody()
		.json("{\"name\":\"Jane\"}");
client.get().uri("/persons/1")
	.exchange()
	.expectStatus().isOk()
	.expectBody()
	.json("{\"name\":\"Jane\"}")

要使用 JSONPath 验证 JSON 内容:spring-doc.cadn.net.cn

client.get().uri("/persons")
		.exchange()
		.expectStatus().isOk()
		.expectBody()
		.jsonPath("$[0].name").isEqualTo("Jane")
		.jsonPath("$[1].name").isEqualTo("Jason");
client.get().uri("/persons")
	.exchange()
	.expectStatus().isOk()
	.expectBody()
	.jsonPath("$[0].name").isEqualTo("Jane")
	.jsonPath("$[1].name").isEqualTo("Jason")

AssertJ集成

RestTestClientResponse 是 AssertJ 集成的主要入口点。 它是一个 AssertProvider,用于包裹交换的 ResponseSpec,以便启用 使用 assertThat() 语句。例如:spring-doc.cadn.net.cn

RestTestClient.ResponseSpec spec = client.get().uri("/persons").exchange();

RestTestClientResponse response = RestTestClientResponse.from(spec);
assertThat(response).hasStatusOk();
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN);
val spec = client.get().uri("/persons").exchange()

val response = RestTestClientResponse.from(spec)
Assertions.assertThat(response).hasStatusOk()
Assertions.assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN)

您也可以先使用内置的工作流,然后获取一个ExchangeResult来包裹并继续使用AssertJ。例如:spring-doc.cadn.net.cn

ExchangeResult result = client.get().uri("/persons").exchange().returnResult();

RestTestClientResponse response = RestTestClientResponse.from(result);
assertThat(response).hasStatusOk();
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN);
val result = client.get().uri("/persons").exchange().returnResult()

val response = RestTestClientResponse.from(result)
Assertions.assertThat(response).hasStatusOk()
Assertions.assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN)