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

Cucumber Java运行截图代码报Scenario类型isFailed()方法未定义错误

报错场景

使用Cucumber Java结合Appium开发iOS/Android跨端自动化测试脚本,实现@AfterStep钩子中失败测试场景自动截图附加到测试报告的功能时,运行代码抛出如下编译错误:

The method isFailed() is undefined for the type Scenario

对应出错的原始实现代码:

package practice.Appium_IOS_Android;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import com.aventstack.extentreports.gherkin.model.Scenario;

import io.cucumber.java.AfterStep;

public class Hooks extends BaseIOS{
    
    @AfterStep
    public void addScreenshot(Scenario scenario){

        //validate if scenario has failed
        if(scenario.isFailed()) {
            final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            scenario.attach(screenshot, "image/png", "image"); 
        }
        
    }

}
错误原因

导包错误:代码中导入的com.aventstack.extentreports.gherkin.model.Scenario是ExtentReports报告库自带的Gherkin数据模型类,并非Cucumber的@AfterStep钩子方法要求注入的Scenario类型。该类没有定义isFailed()、attach()等Cucumber场景对象内置的方法,因此触发方法未定义的编译错误。

修复步骤
  • 删除错误的导包语句:import com.aventstack.extentreports.gherkin.model.Scenario;
  • 新增正确的Cucumber Scenario类导包:import io.cucumber.java.Scenario;

修复后的可正常运行代码如下:

package practice.Appium_IOS_Android;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import io.cucumber.java.AfterStep;
import io.cucumber.java.Scenario;

public class Hooks extends BaseIOS{
    
    @AfterStep
    public void addScreenshot(Scenario scenario){
        // 校验当前步骤执行后场景是否为失败状态
        if(scenario.isFailed()) {
            final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            scenario.attach(screenshot, "image/png", "失败步骤截图"); 
        }
    }
}

注意:如果使用的Cucumber版本低于7.0,attach()方法不存在,需要替换为旧版的embed()方法,参数规则完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 05:39:32