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

繫結到路由函式

此設定允許你透過模擬請求和響應物件測試 函式式端點,而無需執行伺服器。

對於 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")
		.apiVersionInserter(ApiVersionInserter.fromHeader("API-Version").build())
		.build();
client = WebTestClient.bindToController(TestController())
		.configureClient()
		.baseUrl("/test")
		.apiVersionInserter(ApiVersionInserter.fromHeader("API-Version").build())
		.build()

編寫測試

WebClientWebTestClient 在呼叫 exchange() 之前具有相同的 API。之後,WebTestClient 提供了兩種替代方法來驗證響應

  1. 內建斷言 透過一系列期望擴充套件請求工作流

  2. AssertJ 整合 透過 assertThat() 語句驗證響應

有關如何準備包含表單資料、多部分資料等任何內容的請求的示例,請參閱 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()

AssertJ 整合

WebTestClientResponse 是 AssertJ 整合的主要入口點。它是一個 AssertProvider,它包裝了交換的 ResponseSpec,以便啟用 assertThat() 語句的使用。例如

  • Java

  • Kotlin

ResponseSpec spec = client.get().uri("/persons").exchange();

WebTestClientResponse response = WebTestClientResponse.from(spec);
assertThat(response).hasStatusOk();
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN);
// ...
val spec = client.get().uri("/persons").exchange()

val response = WebTestClientResponse.from(spec)
assertThat(response).hasStatusOk()
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN)
// ...

你也可以先使用內建工作流,然後獲取 ExchangeResult 進行包裝並繼續使用 AssertJ。例如

  • Java

  • Kotlin

ExchangeResult result = client.get().uri("/persons").exchange()
		. // ...
		.returnResult();

WebTestClientResponse response = WebTestClientResponse.from(result);
assertThat(response).hasStatusOk();
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN);
// ...
val result = client.get().uri("/persons").exchange()
		. // ...
		.returnResult()

val response = WebTestClientResponse.from(spec)
assertThat(response).hasStatusOk()
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN)
// ...

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"));
© . This site is unofficial and not affiliated with VMware.