RestAssured-将承载令牌从身份验证发送到API查询

时间:2020-03-25 14:59:57

标签: java api oauth rest-assured bearer-token

我刚刚开始使用Rest-assured和API进行功能测试

在Test1中,我通常使用“失眠”进行操作,我进行身份验证并获得访问令牌,

然后在Test2中,我想使用Bearer令牌启动API(就像我在“失眠”中所做的那样)

但是对于如何将其保存为字符串“ accesssToken”并将其正确传递给Test2感到困惑。

   package api_test;

import org.json.JSONObject;
import org.junit.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

public class Api_Authentication {

    @Test(priority=1)
    public void testauth() {

    int code = RestAssured.given()
            .auth().preemptive()
            .basic("username", "password")
            .when()
            .get("https://www.somedomain.com/client_credential/accesstoken?grant_type=client_credentials")
            .getStatusCode();

    System.out.println("Response Code is : " + code);
    Assert.assertEquals(code, 200);

    }

    @Test(priority=2)
    public void testbody() {

        Response resp = RestAssured
                .given()
                .headers(
                        "Authorization", 
                        "Bearer "+ "accessToken", 
                        "Content-Type",
                        ContentType.JSON,
                        "Accept",
                        ContentType.JSON)           
                .get("https://www.somedomain.com/customers?page=1&pageSize=50&name=smith");

        String data = resp.asString();

        System.out.println("Response  = " + data);
        System.out.println("Response  = " + resp.getTime());

    }
}

0 个答案:

没有答案