REST-assured学习笔记

导入pom依赖

    <dependencies>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>2.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.6.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>4.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.13.0</version>
        </dependency>
    </dependencies>
  • get请求
  • post请求
    @Test
    void TestGet() {
        given()
                //设置测试预设
                .header("Hello","World")    //添加请求头信息
                .param("username","HelloWorld")     //添加请求体信息
                .param("id","666")      //添加请求体信息
                .log().all()    //打印完整请求信息
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }


    @Test
    void TestPost() {
        given()
                //设置测试预设
                .header("Hello","World")    //添加请求头信息
                .queryParam("username","HelloWorld")     //添加请求体信息
                .queryParam("id","666")      //添加请求体信息
                .log().all()    //打印完整请求信息
        .when()
                .post("https://httpbin.ceshiren.com/post")    //发送post请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }

断言

  • 响应状态码断言
  • 响应体信息断言
    @Test
    void TestAssertion() {
        given()
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200)   //响应状态码断言
                .body("origin",equalTo("113.118.146.56, 182.92.156.22"));   //响应体信息断言
    }
  • json请求
    • json字符串
    • HashMap对象 + Jackson库
    @Test
    void TestJsonStr() {
        //定义请求数据:jsonStr
        String jsonStr = "{\"hello\":\"World\"}";

        given()
                .contentType("application/json")
                .body(jsonStr)
                .log().headers()    //打印请求头信息
                .log().body()    //打印请求体信息
        .when()
                .post("https://httpbin.ceshiren.com/post")    //发送post请求
        .then()
                .statusCode(200);   //响应状态码断言
    }

    @Test
    void TestJsonObj() {
        //定义请求体数据  HashMap对象
        HashMap<String,String> jsonObj = new HashMap<String, String>();
        jsonObj.put("hello","World");

        given()
                .contentType("application/json")
                .body(jsonObj)
                .log().headers()    //打印请求头信息
                .log().body()    //打印请求体信息
        .when()
                .post("https://httpbin.ceshiren.com/post")    //发送post请求
        .then()
                .statusCode(200);   //响应状态码断言
    }
  • xml请求
	<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
	    <Body>
	        <Add xmlns="http://tempuri.org/">
	            <intA>1</intA>
	            <intB>1</intB>
	        </Add>
	    </Body>
	</Envelope>
    @Test
    void TestXml() throws IOException {
        //定义请求体数据:XML文件
        File file = new File("src/test/resources/add.xml");
        FileInputStream fis = new FileInputStream(file);
        String reqBody = IOUtils.toString(fis,"UTF-8");

        given()
                .contentType("text/xml")    //设定请求内容媒体类型
                .body(reqBody)  //定制请求体数据
                .log().headers()    //打印请求头信息
                .log().body()    //打印请求体信息
        .when()
                .post("http://dneonline.com/calculator.asmx")    //发送post请求
        .then()
                .log().all()
                .statusCode(200);   //响应状态码断言
    }
  • form请求
    @Test
    void TestForm() {
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验
        given()
                //设置测试预设
                //.formParam("form1","value1")    //form表单单数据
                .formParams("username","name","password","pass")    //form表单多数据
                .log().all()    //打印完整请求信息
        .when()
                .post("https://httpbin.ceshiren.com/post")    //发送post请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }
  • xml响应断言
  • json响应断言
    • REST assured内置解析方法
    • 第三方 json-path解析方法
    @Test
    void TestXml() throws IOException {
        //定义请求体数据:XML文件
        File file = new File("src/test/resources/add.xml");
        FileInputStream fis = new FileInputStream(file);
        String reqBody = IOUtils.toString(fis,"UTF-8");

        given()
                .contentType("text/xml")    //设定请求内容媒体类型
                .body(reqBody)  //定制请求体数据
                .log().headers()    //打印请求头信息
                .log().body()    //打印请求体信息
        .when()
                .post("http://dneonline.com/calculator.asmx")    //发送post请求
        .then()
                .log().all()
                .body("//AddResult.text()",equalTo("2"))
                .statusCode(200);   //响应状态码断言
    }

    @Test
    void TestJson() {
        String resp =
                given()
                        .header("Hello","World")
                .when()
                        .get("https://httpbin.ceshiren.com/get")    //发送get请求
                .then()
                        .log().all()    //打印完整响应信息
                        .statusCode(200)
                        .extract().response().asString();   //响应状态码断言
        String word = from(resp).getString("headers.Hello");    //解析响应状态数据
        assertEquals("World",word);
    }

    @Test
    void TestJson2() {
        String resp =
                given()
                        .header("Hello","World")
                .when()
                        .get("https://httpbin.ceshiren.com/get")    //发送get请求
                .then()
                        .log().all()    //打印完整响应信息
                        .statusCode(200)
                        .extract().response().asString();   //响应状态码断言
        String word = JsonPath.read(resp,"$.headers.Hello");    //解析响应状态数据
        assertEquals("World",word);
    }
  • 添加请求头信息
  • 添加cookie信息
    • 通过header()方法
    • 通过cookie()方法
    @Test
    void TestHeader() {
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验
        given()
                //设置测试预设
                .headers("Hello1","World1","Hello2","World2")    //添加请求头信息
                .log().all()    //打印完整请求信息
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }

    @Test
    void TestCookie() {
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验
        given()
                //设置测试预设
                .header("Cookie","my_cookie=HellowWorld")    //添加cookie信息
                .log().all()    //打印完整请求信息
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }

    @Test
    void TestCookie2() {
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验
        given()
                //设置测试预设
                //添加cookie信息
                .cookies("Cookie1","my_cookie1=HellowWorld1","Cookie2","my_cookie2=HellowWorld2")
                .log().all()    //打印完整请求信息
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }

接口超时处理

  1. 创建HttpClientConfig实例
  2. 创建RestAssuredConfig实例
  3. given语句中调用config()方法
    @Test
    void TestDelay() {
        HttpClientConfig clientConfig = HttpClientConfig
                .httpClientConfig()
                .setParam("http.socket.timeout",3000);
        RestAssuredConfig myConfig = RestAssuredConfig.config().httpClient(clientConfig);
        given()
                .config(myConfig)
        .when()
                .get("https://httpbin.ceshiren.com/delay/10")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }

文件上传处理

    @Test
    void TestFile() {
        File myfile = new File("src/test/resources/myText.txt");
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验
        given()
                .multiPart("file",myfile)
                .multiPart("TestJson","{\"name\":\"ZhangSan\"}","applicaton/json")
                .log().all()    //打印完整请求信息
        .when()
                .post("https://httpbin.ceshiren.com/post")    //发送post请求
        .then()
                .log().all()    //打印完整响应信息
                .statusCode(200);   //响应状态码断言
    }

JSON Schema断言

    @Test
    void TestSchema() {
        given()
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all()    //打印完整响应信息
                .assertThat()
                .body(matchesJsonSchemaInClasspath("schema.json")); //JSON Schema断言
    }

代理配置

  • 请求预配置
  • 当前请求配置
    @Test
    void TestHttpsProxy() {
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验

        given()
                //.proxy("127.0.0.1",8888)    //代理地址和端口
                //.relaxedHTTPSValidation()   //忽略HTTPS校验
        .when()
                .get("https://httpbin.ceshiren.com/get")    //发送get请求
        .then()
                .log().all();    //打印完整响应信息
    }

接口加密解密

  • base64加密
  • base64解密
    @Test
    void TestBase64() {
        RestAssured.proxy = host("127.0.0.1").withPort(8888);   //配置本地代理,方便监听请求和响应信息
        RestAssured.useRelaxedHTTPSValidation();    //忽略HTTPS校验
        //定义一个明文数据,使用base64加密传输
        byte[] data = "HelloWorld".getBytes(StandardCharsets.UTF_8);
        String secretMsg = Base64.encodeBase64String(data);
        //获取响应信息中的form存入到LinkedHashMap中
        LinkedHashMap<String,String> respForm = given()
                        .formParam("msg", secretMsg)
                        .when()
                        .post("https://httpbin.ceshiren.com/post")
                        .then()
                        .extract().path("form");
        //获取响应加密文本
        String encodeMsg = respForm.get("msg");
        System.out.println(encodeMsg);
        //把响应中的加密文本转化成解密文本
        byte[] arr = Base64.decodeBase64(encodeMsg);
        String msg = new String(arr,StandardCharsets.UTF_8);
        System.out.println(msg);
    }

多套环境测试

  1. yaml文件预设环境(默认读取环境:default)
  2. 解析yaml文件
  3. 使用RestAssured.baseURI 设置环境信息
	default: org
	org: http://httpbin.org
	test: https://httpbin.ceshiren.com	
    @Test
    void TestEnvs() throws IOException {
        //读取yaml文件所有环境信息
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        File file = new File(classLoader.getResource("envs.yaml").getFile());
        TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {};
        HashMap<String, String> envs = objectMapper.readValue(file, typeReference);
        //把default环境设置为baseURI
        RestAssured.baseURI = envs.get(envs.get("default"));
        given()
        .when()
                .get("/get")    //发送get请求
        .then()
                .log().all();    //打印完整响应信息
    }

最后附上一个企业微信api添加成员案例,使用了分层封装模式:
https://github.com/HandsomeBoy1221/interface-po

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值