java 将屏幕截图附加到 TestNG 失败方法结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11122261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:53:57  来源:igfitidea点击:

Attaching screenshots to TestNG Failed methods results

javaseleniumscreenshottestng

提问by Vlad

I am looking for a way to attach a screenshot to Results section of TestNG Report for the failed methods.

我正在寻找一种方法将屏幕截图附加到失败方法的 TestNG 报告的结果部分。

So far I was able to attache my screenshots to Reporter Output by implementing this:

到目前为止,我能够通过实现以下内容将我的屏幕截图附加到 Reporter Output:

Reporter.log("<br> <img src=.\\screenshots\\" + fileName + " /> <br>");

Reporter.log("<br> <img src=.\\screenshots\\" + fileName + " /> <br>");

but still struggling with adding them to Test Results section of failed methods.

但仍在努力将它们添加到失败方法的测试结果部分。

I was able to implement Listener and intercept onTestFailure actions which was originally suggested here: How can I include a failure screenshot to the testNG report

我能够实现 Listener 并拦截最初在这里建议的 onTestFailure 操作: How can I include a failure screenshot to the testNG report

Here is an example of that:

这是一个例子:

    @Override
public void onTestFailure(ITestResult result) { 
    Reporter.setCurrentTestResult(result); 
    Reporter.log("<br> <img src=.\screenshots\Untitled.png /> <br>");
    Reporter.setCurrentTestResult(null); 
}

But Reporter.log function still pushes my information in the Reporter output log but not in the Results->Failed methods->Failed method log.

但是 Reporter.log 函数仍然将我的信息推送到 Reporter 输出日志中,而不是在结果->失败方法->失败方法日志中。

Update (03/14/14): I've attached screenshot to clarify my question. The problem is not in capturing screenshot and attaching it to Report. That part works fine. The problem is that screenshot is attached to Test Output part of the report but I want to see it in Results -> Failed Methods.

更新(03/14/14):我附上了截图来澄清我的问题。问题不在于捕获屏幕截图并将其附加到报告中。那部分工作正常。问题是屏幕截图附加到报告的测试输出部分,但我想在结果 -> 失败的方法中看到它。

enter image description here

在此处输入图片说明

回答by satish john

I have also implemented the same extending Testng TestListenerAdapter. By capturing the screenshot then attach it to the Testng Report with the image of size height=100 and width=100 with onTestFailure. Please see below if this helps solve your problem

我还实现了相同的扩展 Testng TestListenerAdapter。通过捕获屏幕截图,然后将其附加到 Testng 报告中,图像大小为 height=100 和 width=100,onTestFailure。如果这有助于解决您的问题,请参阅下文

    File scrFile = ((TakesScreenshot) WebdriverManager.globalDriverInstance).getScreenshotAs(OutputType.FILE);
      //Needs Commons IO library
      try {
        FileUtils.copyFile(scrFile, new File(file.getAbsolutePath()+ "/selenium-reports/html/" + result.getName() + ".jpg"));
        Reporter.log("<a href='"+ file.getAbsolutePath()+"/selenium-reports/html/" + result.getName() + ".jpg'> <img src='"+ file.getAbsolutePath()+"/selenium-reports/html/"+ result.getName() + ".jpg' height='100' width='100'/> </a>");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Reporter.setCurrentTestResult(null);

回答by Kamal Chhajed

In addition to above don't forget to add following lines to your testng suite xml

除了以上之外,不要忘记将以下几行添加到您的 testng 套件 xml 中

<listeners>
    <listener class-name="com.tests.DotTestListener" />
</listeners>

OR

或者

passing as listner parameter if you are executing it from command line

如果您从命令行执行它,则作为侦听器参数传递

java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener com.tests.DotTestListener test\testng.xml

Reference : http://testng.org/doc/documentation-main.html#logging-listeners

参考:http: //testng.org/doc/documentation-main.html#logging-listeners

回答by Vinh Trang

I've had same problem but it solved. By implementing SuitePanel you will be able to add screenshot as you want https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/jq/SuitePanel.java

我有同样的问题,但它解决了。通过实施 SuitePanel,您将能够根据需要添加屏幕截图 https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/jq/SuitePanel.java

I almost don't change the original code except

我几乎不改变原始代码,除了

... 
// Description?
String description = tr.getMethod().getDescription();
if (! Strings.isNullOrEmpty(description)) {
    xsb.push("em");
    xsb.addString("(" + description + ")");
    xsb.pop("em");
}
// Add screen shot here
xsb.push(“img”,”src”,imagePath);
xsb.pop(“img”);

xsb.pop(D);
xsb.pop(D);

回答by Mrunal Gosar

If you want to show the screen shot on the failed method then you will have to capture the exception and modify its message content and add img html to that and then it will appear. Let me know if you need example

如果您想在失败的方法上显示屏幕截图,那么您必须捕获异常并修改其消息内容并将 img html 添加到其中,然后它就会出现。如果您需要示例,请告诉我

回答by AnkitSingh

I had same issue but its fixed now. I made a method to catcher screenshot in base class. this method return full path of screenshot.

我有同样的问题,但现在已经解决了。我在基类中创建了一个捕获屏幕截图的方法。此方法返回屏幕截图的完整路径。

public String getScreenshot (String screenshotName, WebDriver driver) throws IOException{
    DateFormat dateformate = new SimpleDateFormat("dd-mm-yy-hh-mm-ss");
    Date date = new Date();
    String currentdate = dateformate.format(date);
    String imageName =screenshotName+currentdate;
    TakesScreenshot ts=(TakesScreenshot)driver;
    File source=ts.getScreenshotAs(OutputType.FILE);
    String location =System.getProperty("user.dir")+"\testOutput\screenshot\"+imageName+".png";
    File screenshotLocation =new File (location);
    FileUtils.copyFile(source, screenshotLocation);
    return location;

}

Add use this path to add screenshot in testng report as well as report log by updating testng TestNgListener-

添加使用此路径通过更新 testng TestNgListener- 在 testng 报告和报告日志中添加屏幕截图

public void onTestFailure(ITestResult arg0) {
    Object currentClass = arg0.getInstance();
    WebDriver driver = ((BrowserSetup) currentClass).getDriver();
    String name = arg0.getName();
    System.out.println(name);
    try {
        String screenshotPath =getScreenshot(name, driver);
        System.out.println("Screenshot taken");
        String path = "<img src=\"file://" + screenshotPath + "\" alt=\"\"/>";
        System.out.println(screenshotPath+" and path - "+path);
        Reporter.log("Capcher screenshot path is "+path);
    } catch (Exception e) {
        System.out.println("Exception while takescreenshot "+e.getMessage());
    }
    printTestResults(arg0);

}

enter image description here

在此处输入图片说明

回答by Nael Marwan

I suggest you to use ReportNG instead of the primitive TestNG reports.

我建议您使用 ReportNG 而不是原始的 TestNG 报告。

回答by Sergiy Matvienko

If the problem only with getting screenshots, you can try to get it like this:

如果问题仅与获取屏幕截图有关,您可以尝试这样获取:

private static byte[] GetCropImg(IWebDriver targetChrome, IWebElement targetElement)
        {
            var screenshot = ((ITakesScreenshot)targetChrome).GetScreenshot();
            var location = targetElement.Location;
            using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
            {
                var rect = new Rectangle(location.X, location.Y, targetElement.Size.Width, targetElement.Size.Height);
                using (Bitmap bmpImage = new Bitmap(stream))
                {
                    using (Bitmap cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat))
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            cropedImag.Save(ms, ImageFormat.Jpeg);

                            byte[] byteImage = ms.ToArray();
                            return byteImage;
                        }
                    }
                }
            }
        }

and then you can save file or save sting64

然后你可以保存文件或保存 sting64

var imgString64 = Convert.ToBase64String(byteImage); //Get Base64

PS: on JAVA it should be almost the same)

PS:在JAVA上应该差不多)