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.