Java 或 Spring Boot 项目需要直接调用 HTTP 接口做集成测试,希望用流式 DSL 描述请求和响应断言,而不是手写 HttpClient。REST Assured 适合接口回归、契约字段校验和带认证的业务链路测试,通常与 JUnit 5 一起运行。
Maven 在 pom.xml 中加入 io.rest-assured:rest-assured:5.5.0,并把 scope 设为 test;做 JSON Schema 校验时再加 io.rest-assured:json-schema-validator,版本保持一致。测试框架依赖见 junit5。
典型结构是 given() 准备请求,when() 发起请求,then() 断言响应。baseUri、basePath、header、contentType、body 放在 given();get、post 等放在 when();statusCode、body、header、time 放在 then()。静态导入 io.restassured.RestAssured.* 和 org.hamcrest.Matchers.* 后代码最简洁。
body("data[0].id", equalTo(1)) 使用 GPath 定位字段,再交给 Hamcrest 匹配器比较。常用匹配器有 equalTo、hasItem、hasSize、not、containsString 和 greaterThan。
需要把响应值传给下一个请求时,用 .extract().path("token") 或 .extract().as(MyResponse.class)。认证可用 .auth().basic("user", "pass")、.auth().oauth2(token),也可以直接设置 Authorization Header。
RestAssured.baseURI、RestAssured.config、日志开关都是全局静态状态。小项目可以在 @BeforeAll 中统一设置,并行测试或一个进程跑多套环境时更适合用 RequestSpecification 按请求隔离。
Rest Assured 默认按响应头解析字符集,接口没有声明 charset 时中文可能乱码;可通过 DecoderConfig、EncoderConfig 指定 UTF-8。请求默认可能长时间等待,必须设置连接和读取超时,例如 given().timeout(5_000)。
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
class UserApiTest {
@Test
void returnsUser() {
given()
.baseUri("http://localhost:8080")
.accept("application/json")
.when()
.get("/api/users/1")
.then()
.statusCode(200)
.header("Content-Type", containsString("application/json"))
.body("id", equalTo(1))
.body("name", not(emptyString()));
}
}
mvn -q test -Dtest=UserApiTest
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
class OrderApiTest {
@Test
void createsOrder() {
given()
.baseUri("http://localhost:8080")
.auth().oauth2(System.getenv("API_TOKEN"))
.contentType(ContentType.JSON)
.body("""
{"sku": "A-1", "quantity": 2}
""")
.when()
.post("/api/orders")
.then()
.statusCode(201)
.body("quantity", equalTo(2));
}
}
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
class UserSchemaTest {
@Test
void matchesSchema() {
given()
.baseUri("http://localhost:8080")
.when()
.get("/api/users/1")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user.json"));
}
}
Schema 文件放在 src/test/resources/schemas/user.json,路径不要加开头的斜杠。
EncoderConfig、DecoderConfig 统一 UTF-8,并确认服务端响应头。.timeout(5_000),并分别考虑连接与读取阶段。baseURI、basePath、日志和过滤器是进程级状态,并行测试或多环境混跑时会互相覆盖;用 RequestSpecification 隔离,或在测试后重置。rest-assured 时 matchesJsonSchemaInClasspath 会找不到类;补充 json-schema-validator 并确认版本一致。src/test/resources,开头加 / 或大小写不一致都会导致资源找不到。Integer、Long 或 Float,用 equalTo(1.0) 比较整数会失败;先确认实际类型或用 closeTo。.body(...),服务端返回 500 但错误结构里恰好有同名字段时仍可能通过;先断言 statusCode。RequestSpecification 反复改 body、header 会保留上一次的值;每个用例重新构建,或使用 spec() 复制。Authorization、Cookie 和密码会进入 CI 日志;只在校验失败时打印,并对敏感 Header 脱敏。given()、when()、then() 分别放什么内容?matchesJsonSchemaInClasspath 前需要额外引入哪个依赖?RestAssured.baseURI?given() 准备请求参数和请求体,when() 发起 HTTP 调用,then() 断言响应。io.rest-assured:json-schema-validator,版本与 REST Assured 保持一致。
小程序版
微信扫码,随时查命令