Cucumber结合REST Assured运行测试持续出现Pending异常如何解决
问题解决方法
错误根因
- 步骤定义方法签名不匹配:@Then注解中使用了
{int}参数占位符,但对应的实现方法没有添加Integer类型的入参,Cucumber无法识别到该步骤的实现。 - 变量引用错误:@Given方法中将提取到的数值列表赋值给了全局变量
x,但@Then方法中遍历的是未定义的numViewsList变量,代码存在编译错误。 - 请求头格式错误:设置请求头时key多写了冒号,正确的请求头key应为
User-Agent而非User-Agent:。 - 原生assert断言默认失效:Java默认关闭assert断言功能,需额外添加JVM参数
-ea才会触发,建议使用测试框架自带的断言方法更稳定。
修复后的步骤定义代码
import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.restassured.RestAssured; import io.restassured.response.Response; import static org.junit.Assert.assertTrue; import java.util.List; public class MyStepdefs { Response response; // 替换无意义的变量名x,改为见名知意的变量名 public List<String> numViewsList; @Given("The API url") public void theAPIUrl() { RestAssured.baseURI = "https://www.colourlovers.com"; String path = "/api/patterns"; response = RestAssured .given() // 去掉请求头key中多余的冒号 .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36") .get(path) .then() .extract() .response(); numViewsList = response.xmlPath().getList("patterns.pattern.numViews"); } // 增加入参接收注解中的{int}占位符数值 @Then("Validates the numValue value greater than {int}") public void validatesTheNumValueValueGreaterThan(Integer threshold) { for (String viewStr : numViewsList) { int numViewsValue = Integer.parseInt(viewStr); // 使用JUnit断言替代原生assert,无需额外配置参数即可生效 assertTrue("存在numViews值小于等于阈值" + threshold, numViewsValue > threshold); } } }
其他检查项
- 确认你的Cucumber启动类的
@CucumberOptions注解中glue属性配置了步骤定义类所在的包路径,确保Cucumber可以扫描到你的步骤实现。 - 确认项目依赖中已经引入了版本兼容的cucumber-java、cucumber-junit、rest-assured、junit依赖。
内容的提问来源于stack exchange,提问作者Mohammad Osama
相关产品推荐
相关产品推荐

