英文:
Authorization Bearer token is not included for request
问题
我正在尝试使用Serenity和Rest-Assured运行我的自动测试,但令牌未包含在我的请求生成方法中。获取令牌本身的方法是正确的。告诉我可能的原因。
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);
}
}
在请求中启动测试时,令牌为null。我尝试使用注解@Before标记,但结果仍然相同。
英文:
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
答案1
得分: 0
你需要将获取令牌的方法移到一个单独的类中,并按以下方式使用它:
NameClass nameClass = new NameClass();
.nameClass.addHeader("Authorization", "Bearer " + getAccessToken())
然后在这个类中使用该方法:
nameClass.getAccessToken()
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论