如何将自定义softAssertion过程中捕获的截图嵌入Cucumber报告?
实现方案
核心逻辑:Cucumber 报告嵌入媒体资源需要依赖执行过程中的Scenario实例提供的资源插入方法,你需要对现有代码做三处调整:
- 改造自定义软断言类,新增
Scenario成员变量接收当前用例场景实例,捕获截图时同步将字节流写入报告
import io.cucumber.java.Scenario; import org.assertj.core.api.SoftAssertions; import org.openqa.selenium.OutputType; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class CustomSoftAssertion extends SoftAssertions { // 新增成员变量存储当前 Cucumber 场景实例 private final Scenario scenario; // 改造构造方法,初始化时传入 Scenario public CustomSoftAssertion(Scenario scenario) { this.scenario = scenario; } @Override public void onAssertionErrorCollected(AssertionError assertionError) { // 直接获取截图字节流用于嵌入报告,减少本地IO操作 byte[] screenshotBytes = TestRunner.appiumDriver.getScreenshotAs(OutputType.BYTES); // 保留原有的本地存储逻辑 File screenshotFile = TestRunner.appiumDriver.getScreenshotAs(OutputType.FILE); try { String savePath = System.getProperty("user.dir") + File.separator + "ScreenShots" + File.separator + LocalDate.now().format(DateTimeFormatter.ofPattern("MMMM_dd_yyyy")) + File.separator + System.currentTimeMillis() + ".png"; // 替换原固定文件名,避免覆盖 FileUtils.copyFile(screenshotFile, new File(savePath), true); } catch (IOException e) { e.printStackTrace(); } // 将截图嵌入 Cucumber 报告 // Cucumber 6及以前版本用下面的写法 scenario.embed(screenshotBytes, "image/png", assertionError.getMessage()); // 如果是Cucumber 7+版本,替换为下面的写法 // scenario.attach(screenshotBytes, "image/png", assertionError.getMessage()); } }
- 在步骤定义类中通过 Cucumber 钩子注入
Scenario实例,初始化自定义软断言对象
import io.cucumber.java.Before; import io.cucumber.java.Scenario; import io.cucumber.java.After; public class StepDefinition { private CustomSoftAssertion softAssertion; private Scenario scenario; // 每个用例执行前注入当前场景实例 @Before public void beforeScenario(Scenario scenario) { this.scenario = scenario; this.softAssertion = new CustomSoftAssertion(scenario); } // 步骤中直接使用初始化好的软断言对象即可 public void checkLoginStatus() { boolean isLogin = true; // 你的业务判断逻辑 softAssertion.assertThat(isLogin).isTrue(); } // 每个用例执行后统一触发软断言校验,避免漏写 @After public void afterScenario() { softAssertion.assertAll(); } }
注意:原代码中截图文件名固定为
demo.png会导致多次断言失败时截图被覆盖,建议用时间戳或者错误信息作为文件名区分
嵌入报告的截图名称可以自定义为断言的错误信息,方便定位具体失败的断言点
内容的提问来源于stack exchange,提问作者DeepakVerma
相关产品推荐
相关产品推荐

