|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
WebTestClient
安装
要设置一个 WebTestClient,您需要选择一个要绑定的服务器设置。这可以是几种模拟服务器设置选项之一,或者连接到一个实时服务器。
绑定到控制器
此设置允许你通过模拟请求和响应对象来测试特定的控制器, 而无需运行服务器。
对于WebFlux应用程序,请使用以下内容,它会加载等效于 WebFlux Java配置的基础结构, 注册给定的 控制器(s),并创建一个 WebHandler链 来处理请求:
-
Java
-
Kotlin
WebTestClient client =
WebTestClient.bindToController(new TestController()).build();
val client = WebTestClient.bindToController(TestController()).build()
对于 Spring MVC,请使用以下内容,它将委托给 StandaloneMockMvcBuilder 以加载等效于 WebMvc Java 配置 的基础设施, 注册给定的控制器,并创建一个 MockMvc 实例来处理请求:
-
Java
-
Kotlin
WebTestClient client =
MockMvcWebTestClient.bindToController(new TestController()).build();
val client = MockMvcWebTestClient.bindToController(TestController()).build()
绑定到ApplicationContext
此设置允许你使用 Spring MVC 或 Spring WebFlux 基础设施和控制器声明加载 Spring 配置,并通过模拟请求和响应对象来处理请求,而无需运行服务器。
对于 WebFlux,请在将 Spring ApplicationContext 传递到
WebHttpHandlerBuilder
以创建处理
WebHandler 链 的请求时使用以下内容:
-
Java
-
Kotlin
@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 ApplicationContext 传递给
MockMvcBuilders.webAppContextSetup
以创建一个用于处理
MockMvc 实例的请求时使用以下内容:
-
Java
-
Kotlin
@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 |
绑定到路由函数
此设置允许您通过模拟请求和响应对象测试 功能端点,而无需运行服务器。
对于 WebFlux,请使用以下代码,它会将 RouterFunctions.toWebHandler 委托给以创建一个处理请求的服务器设置:
-
Java
-
Kotlin
RouterFunction<?> route = ...
client = WebTestClient.bindToRouterFunction(route).build();
val route: RouterFunction<*> = ...
val client = WebTestClient.bindToRouterFunction(route).build()
对于Spring MVC,目前没有选项来测试 WebMvc功能端点。
绑定到服务器
此设置连接到运行中的服务器以执行完整的端到端HTTP测试:
-
Java
-
Kotlin
client = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build();
client = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build()
客户端配置
除了前面描述的服务器设置选项外,您还可以配置客户端选项,包括基础URL、默认头、客户端过滤器等。这些选项在bindToServer()之后可以直接使用。对于所有其他配置选项,您需要使用configureClient()从服务器配置切换到客户端配置,如下所示:
-
Java
-
Kotlin
client = WebTestClient.bindToController(new TestController())
.configureClient()
.baseUrl("/test")
.build();
client = WebTestClient.bindToController(TestController())
.configureClient()
.baseUrl("/test")
.build()
编写测试
WebTestClient 提供了与 WebClient 完全相同的 API,直到使用 exchange() 执行请求为止。有关如何使用任何内容(包括表单数据、多部分数据等)准备请求的示例,请参阅 WebClient 的文档。
在调用 exchange() 之后,WebTestClient 会与 WebClient 分离,并继续执行验证响应的工作流程。
要断言响应状态和头信息,请使用以下方法:
-
Java
-
Kotlin
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)
如果您希望即使其中一个断言失败,所有断言都得到执行,可以使用 expectAll(..) 而不是多个链式调用的 expect*(..)。此功能类似于 AssertJ 中的 软断言 支持以及 JUnit Jupiter 中的 assertAll() 支持。
-
Java
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 内容 或空主体。
并对生成的高级对象执行断言:
-
Java
-
Kotlin
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)
如果内置的断言不够用,你可以直接使用该对象并执行任何其他断言:
-
Java
-
Kotlin
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)...
}
或者您可以退出工作流并获取 EntityExchangeResult:
-
Java
-
Kotlin
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> 的重载方法。 |
没有内容
如果响应预期不包含内容,可以按以下方式断言:
-
Java
-
Kotlin
client.post().uri("/persons")
.body(personMono, Person.class)
.exchange()
.expectStatus().isCreated()
.expectBody().isEmpty();
client.post().uri("/persons")
.bodyValue(person)
.exchange()
.expectStatus().isCreated()
.expectBody().isEmpty()
如果你想忽略响应内容,以下方式会释放内容而没有任何断言:
-
Java
-
Kotlin
client.get().uri("/persons/123")
.exchange()
.expectStatus().isNotFound()
.expectBody(Void.class);
client.get().uri("/persons/123")
.exchange()
.expectStatus().isNotFound
.expectBody<Unit>()
JSON 内容
您可以使用 expectBody() 而不指定目标类型,以对原始内容进行断言,而不是通过高级对象进行。
要使用 JSONAssert 验证完整的 JSON 内容:
-
Java
-
Kotlin
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 内容:
-
Java
-
Kotlin
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",请先验证响应状态和标题,然后
获取一个 FluxExchangeResult:
-
Java
-
Kotlin
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>()
现在您可以通过 StepVerifier 从 reactor-test 消费响应流:
-
Java
-
Kotlin
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 客户端,因此它只能验证客户端响应中的内容,包括状态、头信息和正文。
在使用 MockMvc 服务器设置测试 Spring MVC 应用程序时,你还可以对服务器响应执行进一步的断言。要做到这一点,请在断言正文后获取一个 ExchangeResult:
-
Java
-
Kotlin
// 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 服务器响应断言:
-
Java
-
Kotlin
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"));