Rest-Assured 的响应负载是否可以在多个 类 中存储和使用?

Can Rest-Assured's response payload be stored and used across multiple classes?

有了 Rest-Assured,我发送了一个 GET 请求并得到了正确的响应。然后我可以断言返回了正确的 HTTP 状态代码。

public class MyClass{

  private static Response response;
  RestUtil restUtil = new RestUtil();


  public void sendGetRequestT{
    RequestSpecification httpRequest = given()
            .header("Content-Type", "application/json");

    response = httpRequest
            .when()
            .get(restUtil.getUrl()).andReturn();
  }


 
  public void verifyStatusCode() {
    int statusCode = response.getStatusCode();
    assertThat(response.getStatusCode()).isEqualTo(200);
  }}

因为每次收到新请求时我都需要验证正确的状态码,所以我认为将 verifyStatusCode() 移动到 util class 是一个明智的主意,这样我可以随时调用它,所以我将验证状态码的实现放在单独的 class:

public class RestUtil {
  public static Response response;

  public String url = https://gorest.co.in/public/v1/users;


  public void verify200() {
    int statusCode = response.getStatusCode();
    System.out.println("Status code: " + statusCode);
    assertThat(response.getStatusCode()).isEqualTo(200);

  }

}

现在,在测试 class 中,我调用了 verify200() 方法但得到了 NullPointerException:

public class MyClass{
    
      private static Response response;
      RestUtil restUtil = new RestUtil();
    
    
      
      public void sendGetRequestT{
        RequestSpecification httpRequest = given()
                .header("Content-Type", "application/json");
    
        response = httpRequest
                .when()
                .get(restUtil.getUrl()).andReturn();
      }
    
    
     
      public void verifyStatusCode() {
        restUtil.verify200(); // NullPointerException thrown here
      }}

看起来在多个 class 中使用 response 是不可能的,或者我做错了什么。有什么问题吗?

拥有public个静态变量不是一个好主意。另外,RestUtil中的Response变量与MyClass中的没有关系,所以为null。更好的方法是将 Response 传递到您的 util 方法中,例如:

public class RestUtil {

  public static void verify200(Response response) {
    int statusCode = response.getStatusCode();
    System.out.println("Status code: " + statusCode);
    assertThat(response.getStatusCode()).isEqualTo(200);

  }

}

然后在 MyClass 中:

public class MyClass{
    
      private Response response;
     
      public void sendGetRequestT() {
        RequestSpecification httpRequest = given()
                .header("Content-Type", "application/json");
    
        response = httpRequest
                .when()
                .get(restUtil.getUrl()).andReturn();
      }     
     
      public void verifyStatusCode() {
        RestUtil.verify200( response); 
      }}