rest-assured|Logging实战

一、前言

  在许多情况下,打印响应和/或请求详细信息可能很有用,以帮助您创建正确的期望并发送正确的请求。 为了帮助您做到这一点,您可以使用 REST Assured 提供的预定义过滤器之一,也可以使用其中一种快捷方式。

二、Request Logging(请求日志)

  由于版本 1.5 REST Assured 支持在使用 RequestLoggingFilter 将请求规范发送到服务器之前对其进行记录。 请注意,HTTP 构建器和 HTTP 客户端可能会添加额外的标头,然后打印在日志中。 过滤器只会记录请求规范中指定的详细信息。 IE。 您不能将    RequestLoggingFilter 记录的详细信息视为实际发送到服务器的内容。 此外,后续过滤器可能会在日志记录发生后更改请求。 如果您需要记录线路上实际发送的内容,请参阅 HTTP 客户端日志记录文档或使用外部工具,例如 Wireshark。 例子:

given().log().all(). .. // Log all request specification details including parameters, headers and body
given().log().params(). .. // Log only the parameters of the request
given().log().body(). .. // Log only the request body
given().log().headers(). .. // Log only the request headers
given().log().cookies(). .. // Log only the request cookies
given().log().method(). .. // Log only the request method
given().log().path(). .. // Log only the request path

三、Response Logging(响应日志)

  常用方法如下:

get("/x").then().log().all(). .. 
get("/x").then().log().body() ..
get("/x").then().log().ifError(). .. 
get("/x").then().log().statusLine(). .. // Only log the status line
get("/x").then().log().headers(). .. // Only log the response headers
get("/x").then().log().cookies(). .. // Only log the response cookies

四、Log if validation fails(认证失败日志)

  自rest-assured2.3.1版本起,您可以仅当认证失败时记录请求或者响应的日志。为请求打日志

given().log().ifValidationFails(). ..

  为响应打日志:

.. .then().log().ifValidationFails(). ..

  同时启用对请求和响应的认证失败记录,可以使用LogConfig:

given().config(RestAssured.config().logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails(HEADERS))). ..

  认证失败,仅记录header。

  还有种针对所有请求的简单写法:

RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

五、简单示例

  调用企业微信的发送消息接口,打印请求日志和响应日志

public class TestWeixin {

    public static String access_token;

    @BeforeAll
    public static void getAccesstoken(){
        access_token = given()
                .log().all()
                .params("corpid","wwc376242756245a87","corpsecret","LTnDiVdqHzzmUz8fj21-0kgxv6wEDs3krBnO-0g4MPw")
                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                .then()
                .statusCode(200)
                .log().all()
                .extract().response().path("access_token");

    }

    @Test
    void send_HashMap() {

        //组装content的map
        Map<String,Object> contentMap = new HashMap<> ();
        contentMap.put ( "content","你的快递已到,请携带工卡前往邮件中心领取。
出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
" );

        //组装消息的map
        Map<String,Object> jsonAsMap = new HashMap<> ();
        jsonAsMap.put ( "touser","@all" );
        jsonAsMap.put ( "msgtype","text" );
        jsonAsMap.put ( "agentid",1000002 );
        jsonAsMap.put ( "text", contentMap);

        given()
                .log().all()
                .queryParam("access_token", access_token)
                .contentType(ContentType.JSON)
                .body ( jsonAsMap )
                .post("https://qyapi.weixin.qq.com/cgi-bin/message/send")
                .then()
                .log().all();
    }
}

测试结果:

Request method:    GET
Request URI:    https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwc376242756245a87&corpsecret=LTnDiVdqHzzmUz8fj21-0kgxv6wEDs3krBnO-0g4MPw
Proxy:            <none>
Request params:    corpid=wwc376242756245a88
                corpsecret=LTnDiVdqHzzmUz8fj21-0kgxv6wEDs3krBnO-0g4MPw
Query params:    <none>
Form params:    <none>
Path params:    <none>
Headers:        Accept=*/*
Cookies:        <none>
Multiparts:        <none>
Body:            <none>
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 30 Jun 2021 07:55:50 GMT
Content-Type: application/json; charset=UTF-8
Content-Length: 277
Connection: keep-alive
Error-Code: 0
Error-Msg: ok

{
    "errcode": 0,
    "errmsg": "ok",
    "access_token": "bWTUKz2gxkqMgsMd4Def6ybHU0fF4Zpn-a3LVjHrCtdf-1x7OClrGkvbk2q_AncRvE2oUGqWoqaICzpLvXLA43--MceehKVtmwDPjD4PZ9gcKEjgLCdnrwqvNG75xhfolQ55QIOs59ESNq5OD6wT4itGuMTTIqrAsX2rwv4UVJFMWmk_o7LAU2jjsjoewgMq9OtC78Pp9haQa3n11MR6ww",
    "expires_in": 7200
}

Request method:    POST
Request URI:    https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=bWTUKz2gxkqMgsMd4Def6ybHU0fF4Zpn-a3LVjHrCtdf-1x7OClrGkvbk2q_AncRvE2oUGqWoqaICzpLvXLA43--MceehKVtmwDPjD4PZ9gcKEjgLCdnrwqvNG75xhfolQ55QIOs59ESNq5OD6wT4itGuMTTIqrAsX2rwv4UVJFMWmk_o7LAU2jjsjoewgMq9OtC78Pp9haQa3n11MR6ww
Proxy:            <none>
Request params:    <none>
Query params:    access_token=bWTUKz2gxkqMgsMd4Def6ybHU0fF4Zpn-a3LVjHrCtdf-1x7OClrGkvbk2q_AncRvE2oUGqWoqaICzpLvXLA43--MceehKVtmwDPjD4PZ9gcKEjgLCdnrwqvNG75xhfolQ55QIOs59ESNq5OD6wT4itGuMTTIqrAsX2rwv4UVJFMWmk_o7LAU2jjsjoewgMq9OtC78Pp9haQa3n11MR6ww
Form params:    <none>
Path params:    <none>
Headers:        Accept=*/*
                Content-Type=application/json
Cookies:        <none>
Multiparts:        <none>
Body:
{
    "agentid": 1000002,
    "touser": "@all",
    "text": {
        "content": "你的快递已到,请携带工卡前往邮件中心领取。
出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
"
    },
    "msgtype": "text"
}
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 30 Jun 2021 07:55:52 GMT
Content-Type: application/json; charset=UTF-8
Content-Length: 44
Connection: keep-alive
Error-Code: 0
Error-Msg: ok

{
    "errcode": 0,
    "errmsg": "ok",
    "invaliduser": ""
}

rest-assured官网使用文档:https://github.com/rest-assured/rest-assured/wiki/Usage#examples

知道、想到、做到、得到
原文地址:https://www.cnblogs.com/Durant0420/p/14954888.html