Hard core interface automation testing --- Rest Assured

There are many ways to automate API testing. It can be said that a hundred flowers are blooming. Each approach has its own advantages. So today we will briefly introduce one, which is to realize API automation testing through the combination of Rest Assured and TestNG.

Environment construction

Create a new maven project, configure the following directly in the pom file, import the corresponding packages of Rest Assured and TestNG, and import the latest version according to the actual situation.

        <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.0.5</version>
        </dependency>

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

Demo

Get Demo demo

Here we take the recommended author API on the homepage of Jianshu as an example. This API is a Get request, request address and parameters: http://www.jianshu.com/users/recommended?seen_ids=&count=5&only_unfollowed=true

Then we use Rest Assured to simulate this request,
first we need to import the static method:

import static io.restassured.RestAssured.*;

Then we write our Case:

    @Test()
    public void getHttpTest() {
        Response response = given()
                .get("http://www.jianshu.com/users/recommended?seen_ids=&count=5&only_unfollowed=true");
        // 打印出 response 的body
        response.print();
    }

https protocol Demo

Assuming the https protocol, we take the Douban search book API as an example. The detailed API is shown in the following figure:

 

Douban Book Query

Then in the last case, we followed the parameters directly after the URL to initiate the request. Next, we stripped the parameters and used .params("key","value","key","value"....), and because it was https we need to add ssl configuration, so that all requests support all hostnames:

    @Test()
    public void getHttpsTest() {
        Response response = given()
                // 配置SSL 让所有请求支持所有的主机名
                .config((RestAssured.config().sslConfig(new SSLConfig().relaxedHTTPSValidation())))
                .params("q", "自动化测试", "start", 0, "count", 2)
                .get("https://api.douban.com/v2/book/search");

        // 打印出 response 的body
        response.print();
    }

In addition to the parameters of the request, you can use .params("key","value","key","value"....) to put all the parameters in the parameters(), you can also use parame("key"," value") form.

    @Test()
    public void getHttpsTest2() {
        Response response = given()
                .config((RestAssured.config().sslConfig(new SSLConfig().relaxedHTTPSValidation())))
                .param("q", "自动化测试")
                .param("start", 0)
                .param("count", 2)
                .get("https://api.douban.com/v2/book/search");
        // 打印出 response 的body
        response.print();
    }

Post Demo

Let's take the login API as an example for POST request.
Request method: POST
Protocol: HTTP
Request address: http://XXX.XXXX.com/Home/Login
Request parameters: UserName=xxx&Password=********&CheckCode=&Remember =false&LoginCheckCode=7505 The
request Content-Type is: application/x-www-form-urlencoded
Then the implementation is as follows:

    @Test
    public void postTest2() {

        Response response = given()
                // 设置request Content-Type
                .contentType("application/x-www-form-urlencoded")
                // 请求参数 放body
                .body("UserName=XXXX&Password=XXXXXX&CheckCode=&Remember=false&LoginCheckCode=7505")
                // POST 请求
                .post("http://XXXX.XXXX.com/Home/Login");

        response.print();
    }

Of course, if the request Content-Type type is: application/x-www-form-urlencoded, we can also manage it directly with param() or params(), but if it is
application/json, you can only manage parameters with body().

    @Test
    public void postTest3(){
        Response response = given()
                .contentType("application/x-www-form-urlencoded")
                .param("CheckCode", "")
                .param("LoginCheckCode", "3719")
                .param("Password", "XXXXX")
                .param("Remember", "true")
                .param("UserName", "XXXXX")
                .post("http://XXXX.XXXXX.com/Home/Login");

        response.print();
    }

set header, cookie

The settings of header and cookie are similar to param. There are header(), headers(), cookie(), cookies() methods, which are also similar to param:

        Response response = given()
                .cookie("cookie","value")
                .cookies("cookiename1", "value1", "cookiename2", "value2")
                .header("Accept-Encoding:", "gzip, deflate")
                .headers("header1","value1","header2","value2")
                .get("XXXXXXX");

Get Response status code: StatusCode

Get the status code and return the int type:

response.getStatusCode();

Get Response Cookies

Get a specific cookie:

response.getCookie("cookiesName")

Get all cookies and return a map:

Map cookies = response1.getCookies();

Response headers common operations

  1. Get all headers:

Headers headers = response.getHeaders();
  1. Get the specified header:

response.getHeader("header name");
// 等同上面方法
Headers headers = response.getHeaders();
headers.get("header name");
  1. Determine whether a header exists, return boolean type

Headers headers = response.getHeaders();
headers.hasHeaderWithName("XXX")
  1. Check if header is empty

Headers headers = response.getHeaders();
headers.exist()

Get Response body

Get the Response body and convert it to String type:

response.getBody().asString()

The full example is given along with the JSON parsing below.

Parse JSON

Rest Assured comes with its own support for parsing JSON and xml. For example, we still take the Douban Books Query API as an example. Suppose q= "automatic test" in our request parameters, start=0, count=5, then we simulate this request and do a simple JSON parsing:

    @Test
    public void jsonParsed() {
        Response response = given()
                .config((RestAssured.config().sslConfig(new SSLConfig().relaxedHTTPSValidation())))
                .params("q", "自动化测试", "start", 0, "count", 5)
                .get("https://api.douban.com/v2/book/search");
        // 打印出 response 的body
        response.print();

        int statusCode = response.getStatusCode();
        System.out.println("statusCode:" + statusCode);

        // 获取Response 的所有 headers 并输出
        Headers headers = response.getHeaders();
        System.out.println(headers.toString());

        // 获取Response中header名为Content-Type的值
        String contentType = response.getHeader("Content-Type");
        System.out.println("contentType:" + contentType);
        // 等同上面方法
        System.out.println(headers.get("Content-Type"));

        // 校验某个Header 是否存在
        System.out.println(headers.hasHeaderWithName("fasdfaf"));
        System.out.println(headers.hasHeaderWithName("Server"));

        // 如果Response 的headers不为空则返回true
        System.out.println(headers.exist());

        Map<String, String> cookiesMap = response.cookies();
        for (String key : cookiesMap.keySet()) {
            System.out.println(key + ":" + cookiesMap.get(key));
        }

        System.out.println(response.cookie("bid"));


        // 把Response 的body转成string类型
        System.out.println(response.getBody().asString());

        int count = response.jsonPath().getInt("count");
        System.out.println("count:" + count);

        // 获取所有的 subtitle
        ArrayList<String> subtitles = response.jsonPath().get("books.subtitle");
        for (int i = 0; i < subtitles.size(); i++) {
            System.out.println(subtitles.get(i));
        }

        // 获取特定某个的subtitle
        String subtitle = response.jsonPath().get("books.subtitle[0]");
        System.out.println(subtitle);

        // 获取倒数第二个的subtitle
        String subtitle1 = response.jsonPath().get("books.subtitle[-2]");
        System.out.println(subtitle1);

        // 获取特定tags底下的所有title
        ArrayList<String> tagTitle = response.jsonPath().get("books.tags[2].title");
        for (int i = 0; i < tagTitle.size(); i++) {
            System.out.println(tagTitle.get(i));
        }

        // 获取所有的 title
        ArrayList<ArrayList<String>> tagTitles = response.jsonPath().get("books.tags.title");
        for (int i = 0; i < tagTitles.size(); i++) {
            for (int j = 0; j < tagTitles.get(i).size(); j++) {
                System.out.println(tagTitles.get(i).get(j));
            }
            System.out.println("---------------------");

        }

        // 获取Response json里面所有title = "Selenium 2自动化测试实战"的title
        String title = response.jsonPath().get("books.title.findAll{title ->title==\"Selenium 2自动化测试实战\"}").toString();
        System.out.println(title);

        // 获取Response json中 1< numRaters <=20的所有 numRaters
        String numRaters = response.jsonPath().get("books.rating.numRaters.findAll{numRaters -> numRaters>1 && numRaters<=20}").toString();
        System.out.println(numRaters);

        // 获取Response json种title = "基于Selenium 2的自动化测试"对应的 author
        String title2 = response.jsonPath().get("books.findAll{it.title==\"基于Selenium 2的自动化测试\"}.author").toString();
        System.out.println(title2);

    }

Check if the Response is as expected

Rest Assured provides static methods such as hasITems, is, equalTo for use. When using, import the method first:

import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsEqual.equalTo;

    @Test
    public void testDemo1() {
        Response response = given()
                .config((RestAssured.config().sslConfig(new SSLConfig().relaxedHTTPSValidation())))
                .params("q", "自动化测试", "start", 0, "count", 5)
                .expect()
                // 判断 title是否包含了 自动化 和 自动化测试
                .body("books.tags[2].title", hasItems("自动化", "自动化测试"))
                // 判断 count 值是否为 5
                .body("count", is(5))
                // 判断 publisher 值是否为 "电子工业出版社"
                .body("books.publisher[0]", is("电子工业出版社"))
                // 判断 title 是否等于 5
                .body("count", equalTo(5))
                .when()
                .get("https://api.douban.com/v2/book/search");
        // 打印出 response 的body
        response.print();
    }

Although Rest Assured provides verification methods, in the actual API automated testing process, because there are often many fields to be verified, it is recommended to parse the JSON fields to be verified directly, and then use the Assert class provided by TestNG to perform the verification. check.


add an example

Many API requests in Web API need to be initiated after the user is logged in, and judging whether the user is logged in is often to judge cookies, so if you encounter such problems, you only need to set cookies in the API that needs to be simulated as the login API The generated cookies can be used.
For example, in the demo, the premise of the second request passing is to get the cookies of the first request, then we put all the cookies in the response of the first request into the second request as the request:

    @Test
    public void postHttpsTest3() {
        Response response1 = given()
                .contentType("application/x-www-form-urlencoded")
                .body("UserName=XXXX&Password=XXXXX&CheckCode=&Remember=false&LoginCheckCode=7505")
                .post("http://XXXX.XXXX.com/Home/Login");

        response1.print();
        // 获取reponse中所有的cookies
        Map cookies = response1.getCookies();

        Response response2 = given()
                // 写入第一个请求的cookies
                .cookies(cookies)
                .contentType("application/x-www-form-urlencoded")
                .param("ActionName", "")
                .param("CurrentUserNo", "XXXXX")
                .post("http://XXXX.XXXXX.com/Home/IsCurrentAccountValid");

        response2.print();
    }

Finally, in order to facilitate everyone to learn and test, I specially prepared a 13G super practical dry goods learning resource for everyone, which involves a very comprehensive content.


Including, software learning roadmap, more than 50 days of class videos, 16 assault actual projects, more than 80 software testing software, 37 testing documents, 70 software testing related questions, 40 testing experience-level articles, thousands of copies Sharing of real test questions, as well as the 2021 software test interview collection, as well as various selected resumes for software testing jobs, I hope it will be helpful to everyone...

Follow my official account: [Programmer Er Hei] to get this information!

If you don't want to experience the feeling that you can't find any information during self-study, no one answers your questions, and give up after a few days, you can join our group: 785128166 Let's discuss and exchange together, there are also various software testing materials and technical exchanges.

 

Guess you like

Origin blog.csdn.net/m0_53918927/article/details/119060620