如何跨多个Java方法验证REST保证请求?

时间:2018-09-12 09:42:55

标签: cucumber rest-assured

我正在使用Cucumber编写REST保证测试。

这是我的功能文件:

  

鉴于我想获得一个客户

     

当我请求客户时

     

然后状态代码为“ theStatusCode”

     

返回的ID为“ expectedClientId”

在我的功能文件中的 “ And” 的步骤定义中调用以下方法

public void validateResponseBody(String expectedClientId){
    RestAssured.given()
    .when()
    .get(completeURL)
    .then()
    .statusCode(Integer.parseInt(theStatusCode))
    .and()
    .body("Client.Id", equalTo(expectedClientId));
}

该方法当前有效,但是如何拆分验证?

即我该如何分解以一种方法验证状态代码,并以另一种方法验证客户端ID,而不必两次发送请求?

2 个答案:

答案 0 :(得分:0)

将响应保存到变量:

public void validate() {
    ValidatableResponse response = RestAssured.given()
        .when()
        .get(completeURL)
        .then();

    validateStatusCode(response, statusCode);
    validateResponseBody(response, expectedClientId);
}

public void validateStatusCode(ValidatableResponse response, String statusCode) {
    response
        .statusCode(Integer.parseInt(theStatusCode));
}

public void validateResponseBody(ValidatableResponse response, String expectedClientId) {
    response
        .body("Client.Id", equalTo(expectedClientId));
}

答案 1 :(得分:0)

I suggest to make changes in Feature File. 
New File should be given below. You don't need a when statement here.
Scenario: I want to GET a client  
Given I request a client  
Then the status code is "theStatusCode"  
And the id returned is "expectedClientId"  

@Given("I request a client$")  
public void validate() 
{ 
ValidatableResponse validatableResponse = RestAssured.given()
        .when()
        .get(completeURL)
        .then();
}  
@Then("the status code is \"([^\"]*)\"$") 
public void validateStatusCode(String statusCode) 
{ 
validatableResponse.assertThat().statusCode(Integer.parseInt(theStatusCode));
} 

@And("the id returned is \"([^\"]*)\"$") 
public void validateClientId(String expectedClientId)
{
validatableResponse.assertThat().body("Client.Id", equalTo(expectedClientId));
}