You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移assertThat至BDDStyledMethod类调用Creds报错如何修复

问题根因

报错'Creds(java.lang.String)' in 'steps.Authentication' cannot be applied to '()'由两个代码逻辑错误直接导致:

  • Authentication类中定义的Creds方法签名为public static void Creds(String url),强制要求调用时传入1个字符串类型参数,且方法无返回值;但BDDStyledMethod中写了无参调用Authentication.Creds(),还试图从这个无返回值的方法上读取response属性,不符合方法定义规则。
  • 原Creds方法内的response是方法局部变量,作用域仅限方法内部,外部类无法直接访问该变量。
修正方案

1. 调整Authentication类的Creds方法

将方法返回值从void修改为RestAssured的Response类型,方法执行完成后返回响应对象,移除方法内部冗余的断言,供外部类拿到响应后做自定义校验:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class Authentication {
    public static Response Creds(String url){
        RequestSpecification httpRequest=RestAssured.given()
                .auth().oauth2(Authentication.login("user","password"));

        Response response = httpRequest.get(url);
        ResponseBody body=response.getBody();

        body.prettyPrint();
        System.out.println("The status received: " + response.statusLine());
        return response;
    }

    // 原有login方法保留,此处为占位示例
    private static String login(String user, String password) {
        return "";
    }
}

2. 调整BDDStyledMethod类的调用逻辑

调用Creds方法时传入要求的URL参数,接收方法返回的响应对象完成断言,删除错误的无参调用代码:

import io.restassured.response.Response;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class BDDStyledMethod {

    public static void GetActivityById(){
        Response response = Authentication.Creds("www.randomurl.com");
        assertThat("They are not the same", response.statusLine(), is("HTTP/1.1 200"));
    }
}

可选简化方案

如果不需要在外部类自定义断言逻辑,也可以直接把断言保留在Creds方法内部,BDDStyledMethod中只需要调用传参的Authentication.Creds("www.randomurl.com")即可,无需额外写断言代码。


内容的提问来源于stack exchange,提问作者GetTok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 09:24:16