REST Assured是基于Java的开源接口测试框架,专门为测试RESTful API而设计。它提供了丰富的DSL语法,使得编写接口测试用例更加简洁直观。
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.3.0</version>
</dependency>
import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
RestAssured.baseURI = "https://api.example.com";
RestAssured.port = 443;
@Test
public void testGetUser() {
given()
.header("Authorization", "Bearer token123")
.param("id", 1)
.when()
.get("/users/{id}")
.then()
.statusCode(200)
.body("name", equalTo("张三"))
.body("age", greaterThan(18));
}
@Test
public void testCreateUser() {
String requestBody = "{\"name\":\"李四\",\"age\":25}";
given()
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.post("/users")
.then()
.statusCode(201)
.body("id", notNullValue());
}
@Test
public void testJsonSchema() {
when()
.get("/users/1")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("user-schema.json"));
}
REST Assured的核心源码主要包含以下几个模块:
RestAssured.authentication = oauth2(accessToken);
// 或
RestAssured.authentication = basic(username, password);
given()
.log().all()
.when()
.get("/users")
.then()
.log().body();
given()
.multiPart("file", new File("test.txt"))
.when()
.post("/upload")
.then()
.statusCode(200);
通过合理使用REST Assured框架,可以大大提高接口测试的效率和质量,确保API的稳定性和可靠性。
如若转载,请注明出处:http://www.w-share.com/product/253.html
更新时间:2025-11-29 00:33:52