RestAssured接口自动化框架学习

本文详细介绍RestAssured框架的使用方法,包括环境搭建、基本请求与响应处理、复杂参数设置及结果断言技巧,适合Java接口自动化测试的学习与实践。

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

1.简介

RestAssured是一个java接口自动化测试框架,可以发送POST,GET,PUT,DELETE,OPTIONS,PATCH和HEAD请求,并且可以用来验证和校对这些请求的响应信息。从名称上来看,它可以很好的支对restful风格的接口进行测试。

github地址:https://github.com/rest-assured/rest-assured

Rest Assured是在HTTP Builder(一个软件项目)基础上开发出的一个工具,这个工具能够采用
Java DSL(领域特定语言,例如groovy)进行基于REST风格的服务的测试,使得这种测试变得简单。
2 Rest Assured 支持POST, GET, PUT, DELETE, HEAD, PATCH and OPTIONS这几种类型的请求和响应的验证。没有TRACE类型哈。
1)支持JSON数据解析和验证
2)支持XML数据解析和验证
3)支持cookies添加
4)支持Header字段设置
5)支持Content Type设置
6)正文Body的设置
7)支持Cookies的设置
8)Status状态码相关设置
9)authentication认证设置
 

2.环境搭建及示例

创建一个maven项目,在pom.xml中加入以下依赖


    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.0.1</version>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.0.0</version>
            <scope>test</scope>
        </dependency>

        <!-- use to parse json document -->
        <!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-path</artifactId>
            <version>4.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
        <!-- validate a json response conforms to a Json schema -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>4.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.rest-assured/xml-path -->
        <!-- use to parse xml document -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>xml-path</artifactId>
            <version>4.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
        <!-- match rules in assertion -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>java-hamcrest</artifactId>
            <version>2.0.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.0.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

简单例子

import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.containsString;

/**
 * @description:
 * @author: ljx
 * @time: 2020/6/24 16:56
 */
public class FirstRestAssured {
    @Test
    public void test() {
        //given()这是一个请求对象,get(url)这个是做GET类型请求的发送操作,then()这个是验证相关的对象,前面get()执行完了就能拿到response对
        // 象,然后response对象下有一些验证相关的类,then()就是验证类的一个方法
        //能够打印出响应中一切内容(响应头,cookie,body),而且是比较美观的格式打印,不管响应内容是json还是xml,还是html。
        String url = "https://www.baidu.com";
        given().get(url).then().statusCode(200).log().all();
    }

}

上边的代码完成了请求百度,然后判断状态码并且打印响应信息的操作,可以看出来这种函数式编程十分的便捷,代码量少

given()这是一个请求对象,get(url)这个是做GET类型请求的发送操作,then()这个是验证相关的对象,前面get()执行完了就能拿到response对象,然后response对象下有一些验证相关的类,then()就是验证类的一个方法。

如果使用常规java编程如下:

        /**
	 * Java原本风格的写法
	 */
	@Test
	public void testStatusCodeJavaStyle() {
		//1. 创建一个RestAssured对象
		RestAssured ra = new RestAssured();
		//2. 创建一个请求对象
		RequestSpecification rs = ra.given();
		//3. 发送请求,拿到响应对象
		Response res = rs.get("https://www.baidu.com");
		//4. 判断响应状态码是不是200
		assert res.getStatusCode() == 200;
	}

代码行数比较多。

3.功能详解

1.请求

请求方法之前的部分都是返回请求对象,可以通过param或params添加请求参数,header或headers添加请求头,log().all()打印请求信息

 //带参数请求
        given().param("userId", 2).when().get("http://jsonplaceholder.typicode.com/posts").then().statusCode(200).log().all();
        //带多个参数请求
        HashMap<String,String> param_map = new HashMap<>();
        param_map.put("userId","2");
        param_map.put("id","14");
        given().params(param_map).when().get("http://jsonplaceholder.typicode.com/posts").then().statusCode(200);
        //带请求头,when后返回对象是请求对象可以打印请求信息
        given().header("accept-encoding", "gzip,deflate").param("userId", 2).when().log().all().get("http://jsonplaceholder.typicode.com/posts").then().statusCode(200).log().all();
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("userId", "2");
        parameters.put("id", "14");

        //构造一个Map对象,用来存多个参数和值
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept-encoding", "gzip,deflate");
        headers.put("accept-language", "zh-CN");
        //同时添加header和param,and()可加可不加
        given().headers(headers).and().params(parameters).get("http://jsonplaceholder.typicode.com/posts").then().statusCode(200);

设置多种类型请求参数

 @Test
    public void testMulParams() {
        List<String> list = new ArrayList<String>();
        list.add("one");
        list.add("two");
        given().
                param("key1", "val1", "val2", "val3").
                param("B").
                param("C", list).
                when().
                get("https://xxxx/api/users").
                then().
                statusCode(400);
    }

设置请求contentType,设置请求cookie,设置全局的请求url和bathpath

@Test
    public void testSetContentType() {
        given().
                contentType(ContentType.JSON).
                contentType("applicatipn/json;charset=UTF-8").
                cookie("__utmt", "1").
                when().
                get("http://xxx/xxx").
                then().
                statusCode(404);
        //获取响应时间
        long t = given().get("http://jsonplaceholder.typicode.com/photos/").time();
        System.out.println(t);
        //包装请求参数
        RequestSpecBuilder builder = new RequestSpecBuilder();
        builder.addParam("userId", "2");
        builder.addHeader("Accept-Encoding", "gzip, deflate");
        RequestSpecification requestSpc = builder.build();
        given().
                spec(requestSpc).log().all().
                when().
                get("http://jsonplaceholder.typicode.com/posts").
                then().
                statusCode(200).log().cookies();//log()方法可以打印全部,部分,根据条件选择是否打印
//        basePath, baseURI和port
        RestAssured.baseURI = "http://jsonplaceholder.typicode.com";
        RestAssured.port = 80;
        RestAssured.basePath = "/posts";
        get("/1").then().statusCode(200);

        

    }
@Test
    public void testBasicChallengeAuthentication() {
        //请求接口前先进行账号验证
        given()
                .auth().basic("tom", "123").
                when()
                .get("https://www.xxx.com").
                then()
                .statusCode(200);
    }

请求前进行验证或登录

 

2.响应

请求方法之后的就属于是响应对象

响应内容获取,包含状态码,打印响应内容,获取响应时间,获取响应头,响应类型,响应cookie等

@Test
    public void test_post() {
        //post请求
        given().param("name", "Anthony123").param("job", "tester").header("Content-Type", "text/html").when().post("https://reqres.in/api/users").then().contentType(ContentType.JSON);
        //响应内容格式转换,可以转换为字节数组,字符串,输入流等
        get("https://www.baidu.com").asByteArray();
        get("https://www.baidu.com").asString();
        get("https://www.baidu.com").asInputStream();
        //获取响应中的字段内容,以便拿到数据后做进一步操作
        String url = get("http://jsonplaceholder.typicode.com/photos/1").then().extract().path("url");
        //先获取响应,在进行操作
        Response res = get("http://jsonplaceholder.typicode.com/photos/1").then().extract().response();
        System.out.println(res.path("url"));
        System.out.println(res.getContentType());
        //获取headers
        System.out.println(res.getHeaders());
        Map<String, String> cookies_map = res.getCookies();

    }

响应内容格式转换,请求数据进行序列化,响应数据进行反序列化

 @Test
    public void testDeSerialization() {
        //        序列化就是把对象转换为字节流的过程,反过来,反序列化就是把字节流转换成对象的过程
        User u = new User();
        u.setAge(18);
        u.setWeight(75);
        u.setHome("China");

        UserResponse ur =
                given()
                        .body(u).//restassured内部自动进行序列化,将user对象转换成json
                        when()
                        .post("http://www.thomas-bayer.com/restnames/countries.groovy").
                        as(UserResponse.class);//将响应结果反序列化成java对象,不论响应格式时json还是xml
        // 断言
        ur.setRegId(1101); // 随意设置一个响应数据
        Assert.assertTrue(ur.getRegId() > 0);
        RestAssured.defaultParser = Parser.JSON;//指定全局的解析器位json
        //单独指定解析器
        given().get("http://www.thomas-bayer.com/sqlrest/CUSTOMER/02/").then().using().defaultParser(Parser.XML);

    }

3.结果断言

    @Test
    public void testJson() {
        //匹配json中一个字段的值
        given().get("http://jsonplaceholder.typicode.com/posts/3").then().body("id", equalTo(3));
        String titleString = "ea molestias quasi exercitationem repellat qui ipsa sit aut";
        //匹配json多个值
        given().get("http://jsonplaceholder.typicode.com/posts/3").then().body("id", equalTo(3), "title", equalTo(titleString));
        //匹配json中多个值得第二种写法使用and()
        given().get("http://jsonplaceholder.typicode.com/posts/3").then().body("id", equalTo(3)).and().body("title", equalTo(titleString));
        //部分匹配
        given().get("http://jsonplaceholder.typicode.com/posts/3").then().body("title", containsString("molestias quasi"));

    }

https://www.cnblogs.com/lwjnicole/category/1146558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值