一、前言
在我们做接口自动化的时候,会经常遇到这样的场景,先登录,然后拿到access_token,才能去调用其他的接口,那么rest-assured是如何做到的呢
二、实践
以企业微信登录接口为例
package restassureddemo.weixin; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; public class TestWeixin1 { /* * 企业微信登录接口 * */ @Test public void Login(){ given(). contentType ( ContentType.JSON ) .log().all() //大家自行去注册企业微信账号,并且正确获取corpid和corpsecret .param ( "corpid","wwc376242756245a87" ) .param ( "corpsecret","LTnDiVdqHzzmUz8fj21-0kgxv6wEDs3krBnO-0g4MPw" ) .when () .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken") .then() .statusCode(200) .log().all(); } }
output:
{
"errcode": 0,
"errmsg": "ok",
"access_token": "bWTUKz2gxkqMgsMd4Def6ybHU0fF4Zpn-a3LVjHrCtdf-1x7OClrGkvbk2q_AncRvE2oUGqWoqaICzpLvXLA43--MceehKVtmwDPjD4PZ9gcKEjgLCdnrwqvNG75xhfolQ55QIOs59ESNq5OD6wT4itGuMTTIqrAsX2rwv4UVJFMWmk_o7LAU2jjsjoewgMq9OtC78Pp9haQa3n11MR6ww",
"expires_in": 7200
}
-
获取单个值,直接获取某个值
package restassureddemo.weixin; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; public class TestWeixin1 { /* * 企业微信登录接口 * */ @Test public void Login(){ String access_token = given(). contentType ( ContentType.JSON ) //大家自行去注册企业微信账号,并且正确获取corpid和corpsecret .param ( "corpid","wwc376242756245a88" ) .param ( "corpsecret","LTnDiVdqHzzmUz8fj21-0kgxv6wEDs3krBnO-0g4MPw" ) .when () .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken") .then() .statusCode(200) .extract ().response ().path ( "access_token" ); System.out.println ( "access_token的值为:" + access_token ); } }
-
获取多个值,获取整个response响应体
package restassureddemo.weixin; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; public class TestWeixin1 { /* * 企业微信登录接口 * */ @Test public void Login(){ Response response = given (). contentType ( ContentType.JSON ) //大家自行去注册企业微信账号,并且正确获取corpid和corpsecret .param ( "corpid","wwc376242756245a88" ) .param ( "corpsecret","LTnDiVdqHzzmUz8fj21-0kgxv6wEDs3krBnO-0g4MPw" ) .when () .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken") .then() .statusCode(200) .extract ().response (); String access_token = response.path ( "access_token" ); String errmsg = response.path ( "errmsg" ); System.out.println ( "access_token的值为:" + access_token ); System.out.println ( "errmsg的值为:" + errmsg ); } }
-
获取某个路径下的值,如下面的next
{
"title" : "My Title",
"_links": {
"self": { "href": "/title" },
"next": { "href": "/title?page=2" }
}
}
测试代码:
.extract ().response ().path ( "_links.self.next" );
-
使用JsonPath
-
使用XmlPath