WebTestClient 提供了一个与 WebClient 相同的 API,直至使用 exchange()来执行请求。关于如何准备一个带有任何内容(包括表单数据、多部分数据等)的请求的例子,请参阅 WebClient 文档。
在调用 exchange()之后,WebTestClient 与 WebClient 不同,而是继续使用工作流来验证响应。
要断言响应状态和头文件,请使用以下内容:
client.get().uri("/persons/1").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectHeader().contentType(MediaType.APPLICATION_JSON);
如果你想让所有的期望都被断言,即使其中一个失败了,你可以使用 expectAll(..)而不是多个连锁的 expect*(..) 调用。这个功能类似于 AssertJ 的软断言支持和 JUnit Jupiter 的 assertAll()支持。
client.get().uri("/persons/1").accept(MediaType.APPLICATION_JSON).exchange().expectAll(spec -> spec.expectStatus().isOk(),spec -> spec.expectHeader().contentType(MediaType.APPLICATION_JSON));
然后,你可以选择通过以下方式之一对响应体进行解码:
expectBody(Class<T>):解码为单个对象。expectBodyList(Class<T>):解码并收集对象到List<T>。expectBody():解码为byte[]的 JSON 内容或空。
并对所产生的更高层次的对象执行断言:
client.get().uri("/persons").exchange().expectStatus().isOk().expectBodyList(Person.class).hasSize(3).contains(person);
如果内置的断言是不够的,你可以消耗该对象,并执行任何其他断言:
import org.springframework.test.web.reactive.server.expectBodyclient.get().uri("/persons/1").exchange().expectStatus().isOk().expectBody(Person.class).consumeWith(result -> {// custom assertions (e.g. AssertJ)...});
或者你可以退出工作流并获得一个 EntityExchangeResult:
EntityExchangeResult<Person> result = client.get().uri("/persons/1").exchange().expectStatus().isOk().expectBody(Person.class).returnResult();
:::tips
当你需要用泛型解码到一个目标类型时,寻找接受 ParameterizedTypeReference 而不是 Class<T>的重载方法。
:::
No Content / 没有响应内容
如果不期望响应有内容,你可以按以下方式断言:
client.post().uri("/persons").body(personMono, Person.class).exchange().expectStatus().isCreated().expectBody().isEmpty();
如果你想忽略响应内容,下面的内容是在没有任何断言的情况下释放的:
client.get().uri("/persons/123").exchange().expectStatus().isNotFound().expectBody(Void.class);
JSON Content
你可以在没有目标类型的情况下使用 expectBody() 来执行对原始内容的断言,而不是通过更高级别的 Object(s)。
要用 JSONAssert 验证完整的 JSON 内容:
client.get().uri("/persons/1").exchange().expectStatus().isOk().expectBody().json("{\"name\":\"Jane\"}")
要用 JSONPath 验证 JSON 内容:
client.get().uri("/persons").exchange().expectStatus().isOk().expectBody().jsonPath("$[0].name").isEqualTo("Jane").jsonPath("$[1].name").isEqualTo("Jason");
Streaming Responses
要测试潜在的无限流,如 text/event-stream或 application/x-ndjson,首先要验证响应状态和头文件,然后获得 FluxExchangeResult。
FluxExchangeResult<MyEvent> result = client.get().uri("/events").accept(TEXT_EVENT_STREAM).exchange().expectStatus().isOk().returnResult(MyEvent.class);
现在你已经准备好用 reactor-test 的 StepVerifier 来消费响应流了:
Flux<Event> eventFlux = result.getResponseBody();StepVerifier.create(eventFlux).expectNext(person).expectNextCount(4).consumeNextWith(p -> ...).thenCancel().verify();
MockMvc 的断言
WebTestClient 是一个 HTTP 客户端,因此它只能验证客户端响应中的内容,包括状态、头信息和正文。
当用 MockMvc 服务器设置来测试 Spring MVC 应用程序时,你有额外的选择来对服务器响应进行进一步的断言。要做到这一点,首先要在断言主体后获得 ExchangeResult:
// For a response with a bodyEntityExchangeResult<Person> result = client.get().uri("/persons/1").exchange().expectStatus().isOk().expectBody(Person.class).returnResult();// For a response without a bodyEntityExchangeResult<Void> result = client.get().uri("/path").exchange().expectBody().isEmpty();
然后切换到 MockMvc 服务器响应断言:
MockMvcWebTestClient.resultActionsFor(result).andExpect(model().attribute("integer", 3)).andExpect(model().attribute("string", "a string value"));
