RestAssured框架精讲 – Java接口自动化测试从0到1

前言

大家好,我是Java测开,做Java接口自动化5年。RestAssured是Java生态中最流行的接口测试框架,今天分享RestAssured的实战经验。

一、RestAssured简介

特点

依赖配置

xml

io.rest-assured
rest-assured
5.3.0

二、基础用法

GET请求

java
import static io.restassured.RestAssured.*;

@Test
public void testGetUser() {
given()
.baseUri(“https://api.example.com”)
.header(“Authorization”, “Bearer token”)
.when()
.get(“/users/1”)
.then()
.statusCode(200)
.body(“name”, equalTo(“张三”));
}

POST请求

java
@Test
public void testCreateUser() {
String body = “{“name”:”测试用户”,”email”:”test@example.com”}”;

given()
.contentType(“application/json”)
.body(body)
.when()
.post(“/users”)
.then()
.statusCode(201)
.body(“id”, notNullValue());
}

三、断言详解

java
.then()
// 状态码断言
.statusCode(200)
// 响应时间断言
.time(lessThan(1000L))
// JSON路径断言
.body(“code”, equalTo(200))
.body(“data.size()”, greaterThan(0))
.body(“data[0].name”, containsString(“张”))
// Header断言
.header(“Content-Type”, containsString(“application/json”));

四、数据提取

java
// 提取单个值
String token = given()
.body(“{“username”:”admin”,”password”:”123456″}”)
.when()
.post(“/login”)
.then()
.extract().path(“data.token”);

// 提取完整响应
Response response = given()
.get(“/users”)
.then()
.extract().response();

List names = response.jsonPath().getList(“data.name”);

总结

RestAssured核心要点:

功能 用法
GET请求 given().when().get()
POST请求 given().body().post()
断言 then().body().statusCode()
提取 extract().path()

下期预告:Cucumber行为驱动测试入门 – 让测试用例人人都能读懂

分享到:

探索 RunnerGo 全栈测试平台

RunnerGo 是一款面向企业的全栈测试平台,集接口测试、自动化测试、性能测试、UI测试于一体,助力企业提升研发效能。

接口测试
性能测试
自动化测试
免费体验 RunnerGo