1

我刚刚开始在eclipse中使用TestNG (selenium webdriver)进行自动化。我想捕获屏幕截图并将其显示在测试输出文件夹中的“emailable-report.html”中。我能够捕获屏幕截图并将其保存到系统中的某个位置。但我无法在报告中显示它。报告始终显示“文本”而不​​是图像。

在 TestNG 中,我使用了 ITestListener,它被正确调用。我还摆弄了属性“Reporter.setEscapeHtml”,但没有帮助。

PS:我没用过ReportNG;除非真正需要,否则不打算使用它。

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;

public class TestListener implements ITestListener {
    WebDriver driver = null;
    String filePath = "C:\\opt\\data\\";
    Logger log = Logger.getLogger(TestListener.class.getName());

    @Override
    public void onTestFailure(ITestResult result) {
        log.error("Error " + result.getName() + " test has failed");
        String methodName = result.getName().toString().trim();
        takeScreenShot(methodName);
    }

    public void takeScreenShot(String methodName) {
        driver = getDriver();
        File scrFile =  ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            File f = new File(filePath + methodName + ".png");
            FileUtils.copyFile(scrFile, f);
            log.error("Fail screenshot captured @" + f.getPath() + "");
            //Reporter.setEscapeHtml(true);
            Reporter.log("<img src=\"file:///" + f.getPath() + "\" alt=\"\"/><br />");
        } catch (IOException e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }

    public void onFinish(ITestContext context) {}

    public void onTestStart(ITestResult result) {}

    public void onTestSuccess(ITestResult result) {}

    public void onTestSkipped(ITestResult result) {}

    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}

    public void onStart(ITestContext context) {}

}

4

0 回答 0