WebTestClient
WebTestClient
是一個用於測試伺服器應用的 HTTP 客戶端。它包裝了 Spring 的 WebClient 並使用它來執行請求,但暴露了一個用於驗證響應的測試門面。WebTestClient
可用於執行端到端 HTTP 測試。它還可以透過模擬伺服器請求和響應物件來測試 Spring MVC 和 Spring WebFlux 應用,而無需執行伺服器。
設定
要設定 WebTestClient
,你需要選擇一個伺服器設定進行繫結。這可以是幾種模擬伺服器設定選項之一,也可以是連線到正在執行的伺服器。
繫結到控制器
此設定允許你透過模擬請求和響應物件測試特定的控制器,而無需執行伺服器。
對於 WebFlux 應用,使用以下配置,它載入相當於 WebFlux Java 配置 的基礎設施,註冊給定的控制器,並建立一個 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 |
繫結到 Router Function
此設定允許你透過模擬請求和響應物件測試 函式式端點,而無需執行伺服器。
對於 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("https://:8080").build();
client = WebTestClient.bindToServer().baseUrl("https://: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
-
Kotlin
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) }
)
然後你可以選擇透過以下任一方式解碼響應體
-
expectBody(Class<T>)
: 解碼為單個物件。 -
expectBodyList(Class<T>)
: 解碼並將物件收集到List<T>
中。 -
expectBody()
: 對於 JSON 內容 解碼為byte[]
或空響應體。
並對生成的高階物件執行斷言
-
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 (for example, AssertJ)...
});
client.get().uri("/persons/1")
.exchange()
.expectStatus().isOk()
.expectBody<Person>()
.consumeWith {
// custom assertions (for example, 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>()
現在你可以使用 reactor-test
中的 StepVerifier
來消費響應流了
-
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>()
.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"));