REST-assured是一套由 Java 实现的 REST API 测试框架,语法比较简洁。下面介绍下的基本操作。
一、环境准备
1、pom文件添加依赖
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.4.0</version>
<scope>compile</scope>
</dependency>
2、手动引用静态包
import static io.restassured.RestAssured.*;
3、将RestAssured添加到classPath中
二、RestAssured的基本组成
given:设置场景。 设置测试预设(包括请求头、请求参数、请求体、cookies 等等)
when :执行的操作。所要执行的操作(GET/POST 请求)
注意:如果配置的路径中没有域名,只有相对路径,默认读取本地路径(http://localhost:8080/)
then :产生的结果。解析结果、断言
三、RestAssured样例
1、Get-不带参数的请求
@Test
public void getbase() {
given().
when().get("http://localhost:8080/getBase").
then().log().body();
}
2、Get-带queries参数
@Test
public void getWithProps() {
given().
queryParam("name","Daisy").
queryParam("age","10").
when().get("http://localhost:8080/getWtihQueries").
then().log().body();
}
3、Get-带cookies参数
@Test
public void getWithCookies() {
given().
cookie("login","true").
when().get("/getWithCookies").
then().log().body();
}
4、post-不带参数
@Test
public void postBase() {
given().
when().post("http://localhost:8080/postBase").
then().log().body();
}
5、post-带form参数
@Test
public void postWithForms() {
given().
formParam("name","Daisy").
formParam("age","12").
when().post("http://localhost:8080/postWithForms").
then().log().body();
}
6、post-带json参数
@Test
public void postWithJson() {
String josndata = "{\"name\": \"Daisy\",\"age\": \"10\"}";
given().
body(josndata).contentType(ContentType.JSON)
.when().post("http://localhost:8080/postWithJson")
.then().log().body();
}
7、post-提取响应数据
@Test
public void postGetJson() {
String jsonData = "{\"name\": \"Daisy\",\"age\": \"10\"}";
Response response =
given().
contentType(ContentType.JSON).
body(jsonData).
when().post("http://localhost:8080/postGetCookies").
then().extract().response();
System.out.println("响应时间:" + response.time()); //提取响应时间
System.out.println("cookies:" + response.cookies()); //提取cookies
String result = response.getBody().asString();//提取响应body
}