|
此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 Spring Framework 7.0.6! |
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
import org.junit.jupiter.api.BeforeEach;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.web.servlet.client.RestTestClient;
import org.springframework.web.context.WebApplicationContext;
@SpringJUnitConfig(WebConfig.class) // Specify the configuration to load
public class RestClientContextTests {
RestTestClient client;
@BeforeEach
void setUp(WebApplicationContext context) { // Inject the configuration
// Create the `RestTestClient`
client = RestTestClient.bindToApplicationContext(context).build();
}
}
import org.junit.jupiter.api.BeforeEach
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig
import org.springframework.test.web.servlet.client.RestTestClient
import org.springframework.web.context.WebApplicationContext
@SpringJUnitConfig(WebConfig::class) // Specify the configuration to load
class RestClientContextTests {
lateinit var client: RestTestClient
@BeforeEach
fun setUp(context: WebApplicationContext) { // Inject the configuration
// Create the `RestTestClient`
client = RestTestClient.bindToApplicationContext(context).build()
}
}
绑定到路由函数
此设置允许您通过模拟请求和响应对象来测试函数式端点,而无需启动服务器。
-
Java
-
Kotlin
RouterFunction<?> route = ...
client = RestTestClient.bindToRouterFunction(route).build();
val route: RouterFunction<*> = ...
val client = RestTestClient.bindToRouterFunction(route).build()
编写测试
RestClient 和 RestTestClient 具有相同的 API,直到调用 exchange() 为止。此后,RestTestClient 提供了两种替代方式来验证响应:
-
内置断言 通过一系列期望来扩展请求工作流
-
AssertJ 集成,通过
assertThat()语句验证响应
内置断言
要使用内置的断言,请在调用 exchange() 后继续保持在工作流中,并使用其中一个期望方法。例如:
-
Java
-
Kotlin
client.get().uri("/persons/1")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody();
client.get().uri("/persons/1")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody()
如果你希望即使其中一个断言失败,也能对所有期望进行验证,可以使用 expectAll(..),而不是多次链式调用 expect*(..)。此功能类似于 AssertJ 中的软断言(soft assertions)支持以及 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 内容 解码为#resttestclient-json,或用于空响应体。
如果内置的断言不够用,你可以改为消费该对象,并执行任何其他断言:
-
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();
Person person = result.getResponseBody();
HttpHeaders requestHeaders = result.getRequestHeaders();
val result = client.get().uri("/persons/1")
.exchange()
.expectStatus().isOk
.expectBody<Person>()
.returnResult()
val person: Person? = result.responseBody
val requestHeaders = result.responseHeaders
当您需要解码为带有泛型的目标类型时,请查找接受 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.post().uri("/persons")
.body(person)
.exchange()
.expectStatus().isCreated()
.expectBody(Void.class);
client.get().uri("/persons/123")
.exchange()
.expectStatus().isNotFound
.expectBody<Unit>()
如果你的测试启用了针对池化缓冲区的泄漏检测,那么必须消费响应体(例如,使用 expectBody)。否则,该工具会报告缓冲区发生泄漏。 |
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
RestTestClient.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)
Assertions.assertThat(response).hasStatusOk()
Assertions.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(result)
Assertions.assertThat(response).hasStatusOk()
Assertions.assertThat(response).hasContentTypeCompatibleWith(MediaType.TEXT_PLAIN)