WebTestClient
WebTestClient は、サーバーアプリケーションのテスト用に設計された HTTP クライアントです。これは Spring の WebClient をラップし、それを使用してリクエストを実行しますが、レスポンスを検証するためのテストファサードを公開します。WebTestClient を使用して、エンドツーエンドの HTTP テストを実行できます。また、モックサーバーのリクエストおよびレスポンスオブジェクトを介して、実行中のサーバーなしで Spring MVC および Spring WebFlux アプリケーションをテストするために使用することもできます。
セットアップ
WebTestClient をセットアップするには、バインドするサーバーセットアップを選択する必要があります。これは、いくつかのモックサーバーセットアップの選択肢の 1 つ、またはライブサーバーへの接続のいずれかです。
コントローラーにバインド
この設定により、サーバーを実行せずに、モックリクエストおよびレスポンスオブジェクトを介して特定のコントローラーをテストできます。
WebFlux アプリケーションの場合、WebFlux Java 構成と同等のインフラストラクチャをロードし、指定されたコントローラーを登録し、リクエストを処理するために WebHandler チェーンを作成する以下を使用します。
Java
Kotlin
WebTestClient client =
WebTestClient.bindToController(new TestController()).build();val client = WebTestClient.bindToController(TestController()).build()Spring MVC の場合、次を使用して StandaloneMockMvcBuilder (Javadoc) に委譲し、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 (Javadoc) に渡される場所で以下を使用して、リクエストを処理する 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 (Javadoc) に渡され、リクエストを処理する 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 は、exchange() を使用してリクエストを実行するまで、WebClient と同じ API を提供します。フォームデータ、マルチパートデータなどのコンテンツを含むリクエストを準備する方法の例については、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) いずれかが失敗した場合でもすべての期待値を表明したい場合は、複数のチェーン化された expect*(..) 呼び出しの代わりに expectAll(..) を使用できます。この機能は、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() ジェネリクスを使用してターゲット型にデコードする必要がある場合は、Class<T> ではなく ParameterizedTypeReference (Javadoc) を受け入れるオーバーロードメソッドを探します。 |
コンテンツなし
レスポンスに内容が含まれることが予想されない場合は、次のように主張できます。
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 [GitHub] (英語) で 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"));