WebTestClient
WebTestClient
是一個 HTTP 用戶端,專為測試伺服器應用程式而設計。它封裝了 Spring 的 WebClient 並使用它來執行請求,但公開了一個測試介面以驗證回應。 WebTestClient
可用於執行端對端 HTTP 測試。它也可以用於測試 Spring MVC 和 Spring WebFlux 應用程式,而無需透過 Mock 伺服器請求和回應物件執行伺服器。
設定
要設定 WebTestClient
,您需要選擇要綁定的伺服器設定。這可以是多種 Mock 伺服器設定選擇之一,或是連線到即時伺服器。
綁定到控制器
此設定可讓您透過 Mock 請求和回應物件測試特定的控制器,而無需執行伺服器。
對於 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 組態,並使用它透過 Mock 請求和回應物件處理請求,而無需執行伺服器。
對於 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 |
綁定到路由函數
此設定可讓您透過 Mock 請求和回應物件測試 功能端點,而無需執行伺服器。
對於 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://127.0.0.1:8080").build();
client = WebTestClient.bindToServer().baseUrl("https://127.0.0.1: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
提供的 API 與 WebClient 完全相同,直到使用 exchange()
執行請求為止。請參閱 WebClient 文件,以取得有關如何準備包含表單資料、Multipart 資料等任何內容的請求的範例。
在呼叫 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()
:解碼為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 (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"));