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("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提供了与WebClient完全相同的API,直到使用exchange()执行请求为止。请参阅WebClient文档,了解如何准备包括表单数据、多部分数据等在内的任何内容的请求示例。

在调用exchange()之后,WebTestClientWebClient分歧,而是继续使用工作流来验证响应。

要断言响应状态和头,请使用以下内容:

  • 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中的soft assertions支持和JUnit Jupiter中的assertAll()支持。

  • Java

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 -> {
			// 自定义断言(例如 AssertJ)...
		});
client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody<Person>()
		.consumeWith {
			// 自定义断言(例如 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

// 对有主体的响应
EntityExchangeResult<Person> result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody(Person.class)
		.returnResult();

// 对没有主体的响应
EntityExchangeResult<Void> result = client.get().uri("/path")
		.exchange()
		.expectBody().isEmpty();
// 对有主体的响应
val result = client.get().uri("/persons/1")
		.exchange()
		.expectStatus().isOk()
		.expectBody(Person.class)
		.returnResult();

// 对没有主体的响应
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"));