QA Automation (JAVA). Как полученный токен в первом методе использовать во втором, имея общий класс
Подскажите пожалуйста, как мне правильно передавать полученный токен после авторизации из первого метода bearerTokenAuthenticationTest во все последующие. Попробовал реализовать через глобальную переменную, но во втором методе setGroup не сработало. Понимаю, что что-то не так делаю, но что именно - не понимаю((
public class Authorization {
private static String token;
@Test
public void bearerTokenAuthenticationTest(){
RestAssured.baseURI = "ссылка";
Response response = given()
.contentType(ContentType.JSON)
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("phone", "+78000880860")
.formParam("code", "1234")
.when()
.post("auth/phone/login-by-phone")
.then()
.statusCode(200)
.extract().response();
String jsonString = response.getBody().asString();
String token = JsonPath.from(jsonString).get("accessToken");
response.prettyPrint();
}
@Test
public void setGroup(){
RestAssured.baseURI = "ссылка";
Response response = given()
.contentType(ContentType.JSON)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer " + token)
.formParam("title", "Группа губы")
.when()
.post("/group/save")
.then()
.statusCode(200)
.extract().response();
response.prettyPrint();
}
Ответы (1 шт):
Автор решения: Andrei Popruha
→ Ссылка
Вы можете использовать ThreadLocal, чтобы хранить токен, который может быть использован в любом месте вашего кода.
private static ThreadLocal<String> token = new ThreadLocal<>();
@Test
public void bearerTokenAuthenticationTest(){
RestAssured.baseURI = "ссылка";
Response response = given()
.contentType(ContentType.JSON)
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("phone", "+78000880860")
.formParam("code", "1234")
.when()
.post("auth/phone/login-by-phone")
.then()
.statusCode(200)
.extract().response();
String jsonString = response.getBody().asString();
token.set(JsonPath.from(jsonString).get("accessToken"));
response.prettyPrint();
}
@Test
public void setGroup(){
RestAssured.baseURI = "ссылка";
Response response = given()
.contentType(ContentType.JSON)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer " + token.get())
.formParam("title", "Группа губы")
.when()
.post("/group/save")
.then()
.statusCode(200)
.extract().response();
response.prettyPrint();
}