Eclipse中使用RestAssured时when()方法未定义报错求助
解决RestAssured中
when()方法未定义的问题 我来帮你排查一下这个问题哈,你遇到的The method when() is undefined for the type LastLabTest错误主要有两个核心原因,咱们一步步来解决:
1. RestAssured静态方法未正确导入
when()是RestAssured提供的静态方法,你当前的导入语句import io.restassured.RestAssured;只引入了类本身,没有导入它的静态方法。需要添加带static关键字的导入语句:
// 方式1:单独导入when方法 import static io.restassured.RestAssured.when; // 方式2:一次性导入所有RestAssured静态方法(更推荐,后续用given、then等方法也不用再单独导) import static io.restassured.RestAssured.*;
注意你原来写的import io.restassured.RestAssured.*;是导入类的内部成员,不是静态方法,完全达不到效果哦。
2. JUnit5注解使用错误
你用了JUnit4的@BeforeClass注解,但当前项目用的是JUnit5(JUnit Jupiter),两者的生命周期注解不兼容:
- JUnit5中对应
@BeforeClass的注解是@BeforeAll - 而且
@BeforeAll修饰的方法必须是静态方法,否则无法在类初始化阶段执行 - 同时你的
specification是实例变量,静态方法里无法直接赋值,需要把它改成静态变量
修改后的初始化代码如下:
private static RequestSpecification specification; // 改为静态变量 @BeforeAll // 替换@BeforeClass public static void inItSpec() { // 改为静态方法 specification = new RequestSpecBuilder() .setContentType(ContentType.JSON) .setBaseUri("http://openlibrary.org/") .addFilter(new RequestLoggingFilter()) .addFilter(new ResponseLoggingFilter()) .build(); }
完整修正后的代码
import io.restassured.builder.RequestSpecBuilder; import io.restassured.filter.log.RequestLoggingFilter; import io.restassured.filter.log.ResponseLoggingFilter; import io.restassured.http.ContentType; import io.restassured.specification.RequestSpecification; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.equals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class LastLabTest { private static RequestSpecification specification; @BeforeAll public static void inItSpec() { specification = new RequestSpecBuilder() .setContentType(ContentType.JSON) .setBaseUri("http://openlibrary.org/") .addFilter(new RequestLoggingFilter()) .addFilter(new ResponseLoggingFilter()) .build(); } @Test public void getByName() { when().get("https://swapi.co/api/people/1") .then().log().all() .statusCode(200) .and() .body("name", equals("Luke Skywalker")); } }
另外补充:你原来导入的org.hamcrest.Matchers.*也改成静态导入import static org.hamcrest.Matchers.*;,这样equals()方法才能被正确识别,避免后续出现类似的方法找不到问题。
内容的提问来源于stack exchange,提问作者M.T
相关产品推荐
相关产品推荐

