https://docs.spring.io/spring-framework/reference/testing/webtestclient.html
WebTestClient
是一个专为测试服务器应用程序设计的 HTTP 客户端。它封装了 Spring 的 WebClient
并使用它执行请求,但暴露了一个测试外观以便验证响应。WebTestClient
可以用于执行端到端的 HTTP 测试。它还可以通过模拟服务器请求和响应对象,在不运行服务器的情况下测试 Spring MVC 和 Spring WebFlux 应用程序。
设置
要设置 WebTestClient
,你需要选择一个要绑定的服务器设置。这可以是多个模拟服务器设置选项之一,或者是对实际服务器的连接。
绑定到控制器
这种设置允许你通过模拟请求和响应对象测试特定的控制器,而无需运行服务器。
对于 WebFlux 应用程序,请使用以下方式,它会加载与 WebFlux Java 配置等效的基础设施,注册给定的控制器,并创建 WebHandler 链来处理请求:
WebTestClient client =
WebTestClient.bindToController(new TestController()).build();
对于 Spring MVC,请使用以下方式,它将委托给 StandaloneMockMvcBuilder
来加载与 WebMvc Java 配置等效的基础设施,注册给定的控制器,并创建 MockMvc
的实例来处理请求:
WebTestClient client =
MockMvcWebTestClient.bindToController(new TestController()).build();
绑定到ApplicationContext
这种设置允许你加载带有 Spring MVC 或 Spring WebFlux 基础设施和控制器声明的 Spring 配置,并使用它通过模拟请求和响应对象来处理请求,而无需运行服务器。
对于 WebFlux,使用以下方式,将 Spring ApplicationContext
传递给 WebHttpHandlerBuilder
,以创建用于处理请求的 WebHandler
链:
@SpringJUnitConfig(WebConfig.class)
class MyTests {
WebTestClient client;
@BeforeEach
void setUp(ApplicationContext context) {
client = WebTestClient.bindToApplicationContext(context).build();
}
}
对于 Spring MVC,使用以下方式,将 Spring ApplicationContext
传递给 MockMvcBuilders.webAppContextSetup
,以创建一个 MockMvc
实例来处理请求:
@ExtendWith(SpringExtension.class)
@WebAppConfiguration("classpath:META-INF/web-resources")
@ContextHierarchy({
@ContextConfiguration(classes = RootConfig.class),
@ContextConfiguration(classes = WebConfig.class)
})
class MyTests {
@Autowired
WebApplicationContext wac;
WebTestClient client;
@BeforeEach
void setUp() {
client = MockMvcWebTestClient.bindToApplicationContext(this.wac).build();
}
}
绑定到路由器函数(Bind to Router Function)
这种设置允许你通过模拟请求和响应对象测试功能端点,而无需运行服务器。
对于 WebFlux,使用以下方式,它会委托给 RouterFunctions.toWebHandler
来创建一个服务器设置以处理请求:
RouterFunction<?> route = ...
client = WebTestClient.bindToRouterFunction(route).build();
对于 Spring MVC,目前没有测试 WebMvc 功能端点的选项。
绑定到服务器
这种设置会连接到正在运行的服务器,以执行完整的端到端 HTTP 测试:
client = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build();
客户端配置(Client Config)
除了前面描述的服务器设置选项之外,你还可以配置客户端选项,包括基础 URL、默认头部、客户端过滤器等。这些选项在 bindToServer()
之后就可以使用。对于所有其他配置选项,你需要使用 configureClient()
来从服务器配置过渡到客户端配置,如下所示:
client = WebTestClient.bindToController(new TestController())
.configureClient()
.baseUrl("/test")
.build();
编写测试(Writing Tests)
WebTestClient
提供了一个与 WebClient
相同的 API,直到使用 exchange()
执行请求。
在调用 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 中。expectBody()
:对于 JSON 内容或空体,解码为byte[]
。
并对得到的高级对象执行断言:
client.get().uri("/persons")
.exchange()
.expectStatus().isOk()
.expectBodyList(Person.class).hasSize(3).contains(person);
如果内置断言不够用,你可以代替地消费该对象并执行其他任何断言:
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)...
});
或者,你可以退出工作流并获得一个 EntityExchangeResult
:
EntityExchangeResult<Person> result = client.get().uri("/persons/1")
.exchange()
.expectStatus().isOk()
.expectBody(Person.class)
.returnResult();
当你需要解码为带有泛型的目标类型时,请查找接受 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 内容
你可以在不使用目标类型的情况下使用 expectBody()
对原始内容进行断言,而不是通过高级对象进行断言。
使用 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)
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 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();
然后切换到 MockMvc 服务器响应断言:
MockMvcWebTestClient.resultActionsFor(result)
.andExpect(model().attribute("integer", 3))
.andExpect(model().attribute("string", "a string value"));