gpt4 book ai didi

java - 如何在 testNG 报告中包含失败屏幕截图

转载 作者:搜寻专家 更新时间:2023-11-01 01:08:43 26 4
gpt4 key购买 nike

目前我正在以这种方式截取我的测试失败的屏幕截图:

@AfterMethod(alwaysRun=true)
public void catchExceptions(ITestResult result){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
String methodName = result.getName();
if(!result.isSuccess()){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File((String) PathConverter.convert("failure_screenshots/"+methodName+"_"+formater.format(calendar.getTime())+".png")));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

我可以在 TestNG 报告链接或图片中包含我自己的屏幕截图吗?如果是怎么办?

我在网上找到的只有 FEST 框架。但由于我已经在截屏了,所以我不想使用其他框架。

最佳答案

是的,您可以在 testng 报告中包含指向您的屏幕截图的链接。

您需要调用org.testng.Reporter.log 方法将超链接写入通过使用 @Listeners({yourListener.class}) 注释您的测试类或所有测试类的父类或通过将监听器添加到您的 testng.xml 来报告。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="default">
<listeners>
<listener class-name="ScreenshotListener" />
</listeners>
<test name="Test">
<packages>
<package name="someTests.*"/>
</packages>
</test>
</suite>

需要先创建一个Listener类,添加到testng中。您可以从 testng.org 获得详细信息。搜索听众。

创建该类后,您应该在其中编写一个方法来覆盖 ontestfailure 方法。只要 testng 识别出失败,就会执行此方法中的代码。

您可以调用屏幕截图抓取方法并使用 Reporter.log 将超链接放入该屏幕截图。然后您可以在失败的测试用例详细信息下找到此链接。

import java.io.*;
import java.util.*;
import java.text.*;
import org.apache.commons.io.FileUtils;

import org.openqa.selenium.*;

import org.testng.*;

public class ScreenshotListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
String methodName = result.getName();
if(!result.isSuccess()){
File scrFile = ((TakesScreenshot)SomeStaticWebDriver.driver).getScreenshotAs(OutputType.FILE);
try {
String reportDirectory = new File(System.getProperty("user.dir")).getAbsolutePath() + "/target/surefire-reports";
File destFile = new File((String) reportDirectory+"/failure_screenshots/"+methodName+"_"+formater.format(calendar.getTime())+".png");
FileUtils.copyFile(scrFile, destFile);
Reporter.log("<a href='"+ destFile.getAbsolutePath() + "'> <img src='"+ destFile.getAbsolutePath() + "' height='100' width='100'/> </a>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

关于java - 如何在 testNG 报告中包含失败屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8939337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com