简体   繁体   中英

Authorization Bearer token is not included for request

I am trying to run my autotests with serenity and rest-assured, but the token is not included in my request generation method. The method of getting the token itself works correctly. tell me what could be the reason.

public class ApiSteps {

    private String token;

    public String getAccessToken() {
        RequestSpecification requestSpec = RestAssured.with();
        requestSpec.given().contentType("application/x-www-form-urlencoded");
        Response giveToken = RestAssured.given()
                .formParam("username", "user")
                .formParam("password", "pass")
                .request().post("https://test.com/token");
        DocumentContext doc = JsonPath.parse(giveToken.asString());
        token = doc.read("access_token");
        System.out.println(token);
        return token;
    }

    final RequestSpecification spec = new RequestSpecBuilder()
            .setBaseUri("https://test.com/api/v1")
            .addHeader("Content-Type","application/json")
            .addHeader("Accept", "text/plain")
            .addHeader("Authorization", "Bearer " + getAccessToken())
            .build();

    @Step
    public void testRest() {
        given()
            .spec(spec)
        .when()
            .get("/Test")
        .then()
            .assertThat()
            .statusCode(200);
    }
}

when starting a test in a request - null. I tried to mark with the annotation @Before, but the result is the same

在此处输入图像描述

You need to move the method for getting the token into a separate class and use it as follows:

NameClass nameClass = new NameClass();

.addHeader("Authorization", "Bearer " + getAccessToken())

and here use the method of this class:

nameClass.getAccessToken()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM