使用 Rest-Assured 测试 REST API

本文介绍了如何使用 Rest-Assured 库进行 REST API 的测试,包括添加依赖、编写 JUnit 测试用例、发送带参数的请求、设置 header、cookie 和 content type,解析 JSON 响应以及进行身份验证。同时,提到了 Rest-Assured 对各种 HTTP 请求方法的支持,并给出了官方示例链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pom.xml 
JUnit (根据项目来选择)

<dependency>
  <groupId>com.jayway.restassured</groupId>
  <artifactId>rest-assured</artifactId>
  <version>2.9.0</version>
  <scope>test</scope>
</dependency>

代码示例


import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.*;
import static com.jayway.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
 
public class DouBanTest
{

 @Before
 public void setUP(){
 //指定 URL 和端口号
 RestAssured.baseURI = "http://api.douban.com/v2/book";
 RestAssured.port = 8888;
 }
 
 @Test
 public void testGETBook()
 {

//判断body里的title 是否等于“...”
 get("/1220562").then().body("title", equalTo("lycode"));


 }
 
}

带参数的请求

@Test
 public void testSearchBook(){
 given().param("q", "lycode").when().get("/lycode").then().body("count", equalTo(2));
}

指定 header、cookie、content type

given().cookie("name", "xx").when().get("/xxx").then().body();
given().header("name", "xx").when().get("/xxx").then().body();
given().contentType("application/json").when().get("/xxx").then().body();

解析 JSON 

get("/1220562").then()
//取顶级属性“title”
.body("title", equalTo("lycode"))
//取下一层属性
.body("rating.max", equalTo(10))
//调用数组方法
.body("tags.size()", is(8))
//取数组第一个对象的“name”属性  跟js取json一样
.body("tags[0].name", equalTo("片山恭一"))
//判断数组元素
.body("author", hasItems("[日]"));

身份验证

given().auth().basic(username, password).when().get("/secured").then().statusCode(200);
given().auth().oauth(..);
given().auth().oauth2(..);

其他 HTTP 请求

Rest-Assured 支持所有的标准 HTTP 请求:GET、POST、PUT、DELETE、PATCH、HEAD、OPTION

官方示例 https://github.com/rest-assured/rest-assured

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值