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

如何将测试失败用例截图添加至TestNG测试报告?

如何将失败测试用例的截图嵌入TestNG报告

别慌,我来一步步教你搞定这个需求!核心思路就是用TestNG的监听器捕获测试失败事件,自动触发截图,再把截图的HTML代码插入到TestNG报告里,下面是具体实现步骤:

1. 补全你的截图工具类

先把你写的TakeScreenShot类补全,实现生成截图文件的完整方法:

package library;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class TakeScreenShot {
    private WebDriver driver;

    public TakeScreenShot(WebDriver driver) {
        this.driver = driver;
    }

    // 生成截图并返回截图文件对象
    public File captureScreenshot(String testName) throws IOException {
        // 转换为TakesScreenshot接口
        TakesScreenshot ts = (TakesScreenshot) driver;
        File sourceFile = ts.getScreenshotAs(OutputType.FILE);
        
        // 定义截图保存路径(项目根目录下的screenshots文件夹)
        File destFile = new File(System.getProperty("user.dir") + "/screenshots/" + testName + "_failure.png");
        // 确保父文件夹存在
        destFile.getParentFile().mkdirs();
        // 复制截图到目标路径
        FileUtils.copyFile(sourceFile, destFile);
        
        return destFile;
    }
}

2. 创建TestNG监听器类

TestNG的ITestListener接口可以帮我们监听测试生命周期事件,我们重写onTestFailure方法来实现失败自动截图并嵌入报告:

package listeners;
import java.io.IOException;
import library.TakeScreenShot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class TestFailureListener implements ITestListener {
    private WebDriver driver;

    @Override
    public void onTestFailure(ITestResult result) {
        // 获取当前失败的测试方法名
        String testName = result.getName();
        
        // 从测试类实例中获取WebDriver(假设你的测试类里有driver成员变量)
        Object testClass = result.getInstance();
        if (testClass != null) {
            try {
                driver = (WebDriver) testClass.getClass().getDeclaredField("driver").get(testClass);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }

        // 生成截图并插入报告
        TakeScreenShot screenshotUtil = new TakeScreenShot(driver);
        try {
            screenshotUtil.captureScreenshot(testName);
            // 拼接截图的HTML标签,插入到失败描述中
            String relativePath = "./screenshots/" + testName + "_failure.png";
            String failureMsg = result.getThrowable().toString();
            String screenshotHtml = "<br><b>Failure Screenshot:</b><br><img src=\"" + relativePath + "\" width=\"800\" height=\"600\">";
            result.setThrowable(new Throwable(failureMsg + screenshotHtml));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 其他接口方法留空即可
    @Override
    public void onTestStart(ITestResult result) {}
    @Override
    public void onTestSuccess(ITestResult result) {}
    @Override
    public void onTestSkipped(ITestResult result) {}
    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}
    @Override
    public void onStart(ITestContext context) {}
    @Override
    public void onFinish(ITestContext context) {}
}

3. 配置TestNG使用监听器

有两种方式让TestNG启用这个监听器:

方式1:在testng.xml中配置

<suite name="Your Test Suite">
    <listeners>
        <listener class-name="listeners.TestFailureListener"/>
    </listeners>
    <test name="Your Test">
        <!-- 你的测试类/方法配置 -->
    </test>
</suite>

方式2:在测试类上添加注解

直接在你的测试类顶部加上@Listeners注解:

import listeners.TestFailureListener;
import org.testng.annotations.Listeners;

@Listeners(TestFailureListener.class)
public class YourTestClass {
    // 测试方法代码...
}

4. 验证效果

运行TestNG测试后,失败的用例会自动在项目根目录的screenshots文件夹生成截图。打开TestNG报告(默认在test-output/index.html),找到失败的测试用例,就能看到嵌入的截图啦!

小提醒

  • 确保项目引入了commons-io依赖(因为用到了FileUtils),Maven可以在pom.xml里加:
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.1</version>
</dependency>
  • 如果你的WebDriver用ThreadLocal管理,记得在监听器里调整Driver的获取方式,避免线程安全问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:20:02