RestTestClient

RestTestClient 是一個專為測試伺服器應用而設計的 HTTP 客戶端。它封裝了 Spring 的 RestClient 並用它來執行請求,但提供了一個測試門面用於驗證響應。RestTestClient 可以用於執行端到端 HTTP 測試。它也可以透過 MockMvc 在沒有執行伺服器的情況下測試 Spring MVC 應用。

設定

要設定 RestTestClient,你需要選擇一個伺服器設定進行繫結。這可以是幾種 MockMvc 設定選擇之一,或者是連線到即時伺服器。

繫結到控制器

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

  • Java

  • Kotlin

RestTestClient client =
		RestTestClient.bindToController(new TestController()).build();
val client = RestTestClient.bindToController(TestController()).build()

繫結到 ApplicationContext

此設定允許你載入包含 Spring MVC 基礎設施和控制器宣告的 Spring 配置,並使用它透過模擬請求和響應物件處理請求,而無需執行伺服器。

  • Java

  • Kotlin

@SpringJUnitConfig(WebConfig.class) (1)
class MyTests {

	RestTestClient client;

	@BeforeEach
	void setUp(ApplicationContext context) {  (2)
		client = RestTestClient.bindToApplicationContext(context).build(); (3)
	}
}
1 指定要載入的配置
2 注入配置
3 建立 RestTestClient
@SpringJUnitConfig(WebConfig::class) (1)
class MyTests {

	lateinit var client: RestTestClient

	@BeforeEach
	fun setUp(context: ApplicationContext) { (2)
		client = RestTestClient.bindToApplicationContext(context).build() (3)
	}
}
1 指定要載入的配置
2 注入配置
3 建立 RestTestClient

繫結到路由器函式

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

  • Java

  • Kotlin

RouterFunction<?> route = ...
client = RestTestClient.bindToRouterFunction(route).build();
val route: RouterFunction<*> = ...
val client = RestTestClient.bindToRouterFunction(route).build()

繫結到伺服器

此設定連線到正在執行的伺服器以執行完整的端到端 HTTP 測試

  • Java

  • Kotlin

client = RestTestClient.bindToServer().baseUrl("https://:8080").build();
client = RestTestClient.bindToServer().baseUrl("https://:8080").build()

客戶端配置

除了前面描述的伺服器設定選項之外,你還可以配置客戶端選項,包括基本 URL、預設頭、客戶端過濾器等。這些選項在首次呼叫 bindTo 之後即可使用,如下所示

  • Java

  • Kotlin

client = RestTestClient.bindToController(new TestController())
		.baseUrl("/test")
		.build();
client = RestTestClient.bindToController(TestController())
		.baseUrl("/test")
		.build()

編寫測試

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

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

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

內建斷言

要使用內建斷言,請在呼叫 exchange() 後保持在工作流中,並使用其中一個期望方法。例如

  • 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>): 解碼為單個物件。

  • expectBody(): 解碼為 JSON 內容byte[] 或空體。

如果內建斷言不足,你可以選擇消費物件並執行任何其他斷言

  • Java

  • Kotlin

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();
val result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk
		.expectBody<Person>()
		.returnResult()
當你需要解碼為帶有泛型的目標型別時,請查詢接受 ParameterizedTypeReference 而不是 Class<T> 的過載方法。

無內容

如果響應預計沒有內容,你可以按如下方式斷言

  • Java

  • Kotlin

client.post().uri("/persons")
		.body(person)
		.exchange()
		.expectStatus().isCreated()
		.expectBody().isEmpty();
client.post().uri("/persons")
		.body(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")

AssertJ 整合

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

  • Java

  • Kotlin

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

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

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

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

  • Java

  • Kotlin

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

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

val response = RestTestClientResponse.from(spec)
assertThat(response).hasStatusOk()
assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN)
// ...
© . This site is unofficial and not affiliated with VMware.