此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.1.10Spring中文文档

此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.1.10Spring中文文档

WebTestClient是专为测试服务器应用程序而设计的 HTTP 客户端。它包裹着 Spring 的 WebClient 并使用它来执行请求 但公开了用于验证响应的测试外观。 可用于 执行端到端 HTTP 测试。它还可用于测试 Spring MVC 和 Spring WebFlux 没有运行服务器的应用程序,通过模拟服务器请求和响应对象。WebTestClientSpring中文文档

Kotlin 用户:请参阅 .WebTestClient
Kotlin 用户:请参阅 .WebTestClient

设置

要设置,您需要选择要绑定到的服务器设置。这可以是一个 多个模拟服务器设置选项或与实时服务器的连接。WebTestClientSpring中文文档

绑定到控制器

此设置允许您通过模拟请求和响应对象测试特定控制器, 没有正在运行的服务器。Spring中文文档

对于 WebFlux 应用程序,请使用以下命令加载与 WebFlux Java 配置等效的基础结构,注册给定的 控制器,并创建一个 WebHandler 链来处理请求:Spring中文文档

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

对于 Spring MVC,请使用以下委托给 StandaloneMockMvcBuilder 来加载与 WebMvc Java 配置等效的基础结构, 注册给定的控制器,并创建一个 MockMvc 实例来处理请求:Spring中文文档

WebTestClient client =
		MockMvcWebTestClient.bindToController(new TestController()).build();
val client = MockMvcWebTestClient.bindToController(TestController()).build()

绑定到ApplicationContext

此设置允许您使用 Spring MVC 或 Spring WebFlux 加载 Spring 配置 基础架构和控制器声明,并使用它来通过模拟请求处理请求 和响应对象,没有正在运行的服务器。Spring中文文档

对于 WebFlux,请使用以下命令将 Spring 传递给 WebHttpHandlerBuilder,以创建要处理的 WebHandler 链 请求:ApplicationContextSpring中文文档

@SpringJUnitConfig(WebConfig.class) (1)
class MyTests {

	WebTestClient client;

	@BeforeEach
	void setUp(ApplicationContext context) {  (2)
		client = WebTestClient.bindToApplicationContext(context).build(); (3)
	}
}
1 指定要加载的配置
2 注入配置
3 创建WebTestClient
@SpringJUnitConfig(WebConfig::class) (1)
class MyTests {

	lateinit var client: WebTestClient

	@BeforeEach
	fun setUp(context: ApplicationContext) { (2)
		client = WebTestClient.bindToApplicationContext(context).build() (3)
	}
}
1 指定要加载的配置
2 注入配置
3 创建WebTestClient

对于 Spring MVC,请使用以下命令将 Spring 传递给 MockMvcBuilders.webAppContextSetup 以创建要处理的 MockMvc 实例 请求:ApplicationContextSpring中文文档

@ExtendWith(SpringExtension.class)
@WebAppConfiguration("classpath:META-INF/web-resources") (1)
@ContextHierarchy({
	@ContextConfiguration(classes = RootConfig.class),
	@ContextConfiguration(classes = WebConfig.class)
})
class MyTests {

	@Autowired
	WebApplicationContext wac; (2)

	WebTestClient client;

	@BeforeEach
	void setUp() {
		client = MockMvcWebTestClient.bindToApplicationContext(this.wac).build(); (3)
	}
}
1 指定要加载的配置
2 注入配置
3 创建WebTestClient
@ExtendWith(SpringExtension.class)
@WebAppConfiguration("classpath:META-INF/web-resources") (1)
@ContextHierarchy({
	@ContextConfiguration(classes = RootConfig.class),
	@ContextConfiguration(classes = WebConfig.class)
})
class MyTests {

	@Autowired
	lateinit var wac: WebApplicationContext; (2)

	lateinit var client: WebTestClient

	@BeforeEach
	fun setUp() { (2)
		client = MockMvcWebTestClient.bindToApplicationContext(wac).build() (3)
	}
}
1 指定要加载的配置
2 注入配置
3 创建WebTestClient

绑定路由器功能

此设置允许您通过以下方式测试功能端点 模拟请求和响应对象,没有正在运行的服务器。Spring中文文档

对于 WebFlux,请使用以下命令,将委托给 创建服务器设置以处理请求:RouterFunctions.toWebHandlerSpring中文文档

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

对于 Spring MVC,目前没有用于测试 WebMvc 功能终结点的选项。Spring中文文档

绑定到服务器

此设置连接到正在运行的服务器以执行完整的端到端 HTTP 测试:Spring中文文档

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

客户端配置

除了前面所述的服务器设置选项外,您还可以配置客户端 选项,包括基本 URL、默认标头、客户端筛选器等。这些选项 在以下情况下随时可用。对于所有其他配置选项, 您需要使用从服务器配置转换到客户端配置,如 遵循:bindToServer()configureClient()Spring中文文档

client = WebTestClient.bindToController(new TestController())
		.configureClient()
		.baseUrl("/test")
		.build();
client = WebTestClient.bindToController(TestController())
		.configureClient()
		.baseUrl("/test")
		.build()
1 指定要加载的配置
2 注入配置
3 创建WebTestClient
1 指定要加载的配置
2 注入配置
3 创建WebTestClient
1 指定要加载的配置
2 注入配置
3 创建WebTestClient
1 指定要加载的配置
2 注入配置
3 创建WebTestClient

编写测试

WebTestClient提供与 WebClient 相同的 API,直到使用 执行请求。有关如何执行以下操作的示例,请参阅 WebClient 文档 准备包含任何内容(包括表单数据、分段数据等)的请求。exchange()Spring中文文档

在调用 之后,与 和 而是继续使用工作流来验证响应。exchange()WebTestClientWebClientSpring中文文档

若要断言响应状态和标头,请使用以下命令:Spring中文文档

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

如果您希望断言所有期望,即使其中一个失败了,您也可以 使用代替多个链式调用。此功能是 类似于 AssertJ 中的软断言支持和 AssertJ 中的支持 JUnit 木星。expectAll(..)expect*(..)assertAll()Spring中文文档

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

然后,您可以选择通过以下方法之一对响应正文进行解码:Spring中文文档

并对生成的更高级别的对象执行断言:Spring中文文档

client.get().uri("/persons")
		.exchange()
		.expectStatus().isOk()
		.expectBodyList(Person.class).hasSize(3).contains(person);
import org.springframework.test.web.reactive.server.expectBodyList

client.get().uri("/persons")
		.exchange()
		.expectStatus().isOk()
		.expectBodyList<Person>().hasSize(3).contains(person)

如果内置断言不足,则可以改用对象,然后 执行任何其他断言:Spring中文文档

   import org.springframework.test.web.reactive.server.expectBody

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

或者,您可以退出工作流并获得:EntityExchangeResultSpring中文文档

EntityExchangeResult<Person> result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody(Person.class)
		.returnResult();
import org.springframework.test.web.reactive.server.expectBody

val result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk
		.expectBody<Person>()
		.returnResult()
当需要使用泛型解码为目标类型时,请查找重载方法 接受 ParameterizedTypeReference 而不是 .Class<T>

暂无内容

如果响应不应包含内容,则可以按如下方式断言:Spring中文文档

client.post().uri("/persons")
		.body(personMono, Person.class)
		.exchange()
		.expectStatus().isCreated()
		.expectBody().isEmpty();
client.post().uri("/persons")
		.bodyValue(person)
		.exchange()
		.expectStatus().isCreated()
		.expectBody().isEmpty()

如果要忽略响应内容,以下内容将不带 任何断言:Spring中文文档

client.get().uri("/persons/123")
		.exchange()
		.expectStatus().isNotFound()
		.expectBody(Void.class);
client.get().uri("/persons/123")
		.exchange()
		.expectStatus().isNotFound
		.expectBody<Unit>()

JSON 内容

您可以在没有目标类型的情况下使用对原始数据执行断言 内容,而不是通过更高级别的对象。expectBody()Spring中文文档

要使用 JSONAssert 验证完整的 JSON 内容,请执行以下操作:Spring中文文档

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中文文档

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")

流式响应

要测试潜在的无限流(如 或),首先验证响应状态和标头,然后 获得:"text/event-stream""application/x-ndjson"FluxExchangeResultSpring中文文档

FluxExchangeResult<MyEvent> result = client.get().uri("/events")
		.accept(TEXT_EVENT_STREAM)
		.exchange()
		.expectStatus().isOk()
		.returnResult(MyEvent.class);
import org.springframework.test.web.reactive.server.returnResult

val result = client.get().uri("/events")
		.accept(TEXT_EVENT_STREAM)
		.exchange()
		.expectStatus().isOk()
		.returnResult<MyEvent>()

现在,你已准备好使用来自以下位置的响应流:StepVerifierreactor-testSpring中文文档

Flux<Event> eventFlux = result.getResponseBody();

StepVerifier.create(eventFlux)
		.expectNext(person)
		.expectNextCount(4)
		.consumeNextWith(p -> ...)
		.thenCancel()
		.verify();
val eventFlux = result.getResponseBody()

StepVerifier.create(eventFlux)
		.expectNext(person)
		.expectNextCount(4)
		.consumeNextWith { p -> ... }
		.thenCancel()
		.verify()

MockMvc 断言

WebTestClient是一个 HTTP 客户端,因此它只能验证客户端中的内容 响应,包括状态、标头和正文。Spring中文文档

使用 MockMvc 服务器设置测试 Spring MVC 应用程序时,您有额外的 选择对服务器响应执行进一步的断言。要做到这一点,首先要 在断言正文后获得:ExchangeResultSpring中文文档

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

// For a response without a body
EntityExchangeResult<Void> result = client.get().uri("/path")
		.exchange()
		.expectBody().isEmpty();
// For a response with a body
val result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody(Person.class)
		.returnResult();

// For a response without a body
val result = client.get().uri("/path")
		.exchange()
		.expectBody().isEmpty();

然后切换到 MockMvc 服务器响应断言:Spring中文文档

MockMvcWebTestClient.resultActionsFor(result)
		.andExpect(model().attribute("integer", 3))
		.andExpect(model().attribute("string", "a string value"));
MockMvcWebTestClient.resultActionsFor(result)
		.andExpect(model().attribute("integer", 3))
		.andExpect(model().attribute("string", "a string value"));
当需要使用泛型解码为目标类型时,请查找重载方法 接受 ParameterizedTypeReference 而不是 .Class<T>