REST-assured 接口测试编写指南
REST-assured 简介
REST-assured 是一个基于 Java 的 DSL(领域特定语言)库,专门用于简化 RESTful API 测试的编写。它提供了流畅的 API 接口,使得测试代码更加易读易写,支持 JSON 和 XML 等多种响应格式的验证。
基本环境配置
-
Maven 依赖配置:
<dependency><groupId>io.rest-assured</groupId><artifactId>rest-assured</artifactId><version>5.3.0</version><scope>test</scope> </dependency>
详情见:https://blog.csdn.net/Y1_again_0_again/article/details/148828971?spm=1011.2415.3001.5331
-
静态导入(简化代码):
import static io.restassured.RestAssured.*; import static io.restassured.matcher.RestAssuredMatchers.*; import static org.hamcrest.Matchers.*;
基础测试代码示例
GET 请求测试
@Test
public void testGetUser() {given().param("userId", "12345") // 设置查询参数.when().get("https://api.example.com/users") // 发送GET请求.then().statusCode(200) // 验证状态码.body("name", equalTo("John")) // 验证响应体中的name字段.body("age", greaterThan(18)); // 验证age字段大于18
}
POST 请求测试
@Test
public void testCreateUser() {String requestBody = "{\"name\":\"Alice\",\"age\":25}";given().contentType(ContentType.JSON) // 设置请求头.body(requestBody) // 设置请求体.when().post("https://api.example.com/users") // 发送POST请求.then().statusCode(201) // 验证创建成功.body("id", notNullValue()); // 验证响应中包含id字段
}
高级用法
认证设置
given().auth().basic("username", "password") // 基本认证// 或 .auth().oauth2("access_token") // OAuth2认证
.when().get("/secure-endpoint")
.then().statusCode(200);
JSON Schema 验证
@Test
public void testJsonSchema() {when().get("/products/1").then().assertThat().body(matchesJsonSchemaInClasspath("product-schema.json"));
}
文件上传
given().multiPart("file", new File("test.png")) // 上传文件
.when().post("/upload")
.then().statusCode(200);
最佳实践
-
基础URL配置:
RestAssured.baseURI = "https://api.example.com"; RestAssured.basePath = "/v1";
-
日志记录:
given().log().all() // 记录请求详情 .when().get("/resource") .then().log().body(); // 记录响应体
-
响应时间验证:
when().get("/resource") .then().time(lessThan(2000L)); // 响应时间应小于2秒
-
使用JSONPath提取值:
String userId = given().param("name", "John") .when().get("/users") .then().extract().path("[0].id"); // 提取第一个用户的id
常见验证场景
- 验证状态码:
.statusCode(200)
- 验证响应头:
.header("Content-Type", containsString("application/json"))
- 验证数组大小:
.body("users.size()", equalTo(3))
- 验证数组元素:
.body("users[0].name", equalTo("John"))
- 验证响应时间:
.time(lessThan(2000L))
通过以上示例和方法,可以构建完整的API测试套件,覆盖各种测试场景。REST-assured编写代码进行接口测试