TestNG失败用例自动截图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TestNG失败用例自动截图相关的知识,希望对你有一定的参考价值。

参考:https://blog.csdn.net/wangxin1982314/article/details/50247245

1. 首先写一个截屏方法 

 1 public class ScreenShotOnFailure {
 2     public static final String SCREEN_SHOT_PATH = "test-output/screen-shot";
 3     public static String SCREEN_SHOT_NAME = null;
 4     
 5     public static void takeScreenShot() throws IOException {
 6         File screenshotDir = new File(SCREEN_SHOT_PATH);
 7         if(!screenshotDir.exists()) {
 8             screenshotDir.mkdirs();
 9         }
10         
11         SimpleDateFormat smf = new SimpleDateFormat("yyyyMMddHHmmss");        
12         SCREEN_SHOT_NAME = String.valueOf(smf.format(new Date())) + ".jpg";
13         FileUtils.copyFile(((TakesScreenshot)browser.getWebDriver()).getScreenshotAs(OutputType.FILE),
14                 new File(SCREEN_SHOT_PATH + "/"+ SCREEN_SHOT_NAME));    
15     }
16 }

 

2. 新建一个监听类,重写onTestFailure方法  

 1 import org.testng.ITestContext;
 2 import org.testng.ITestListener;
 3 import org.testng.ITestResult;
 4 import static com.crewbudget.bean.ScreenShotOnFailure.SCREEN_SHOT_NAME;
 5 import static com.crewbudget.bean.ScreenShotOnFailure.SCREEN_SHOT_PATH;
 6 
 7 public class TestngRetryListener implements ITestListener{
 8     public void onTestFailure(ITestResult result) {
 9         try {
10             ScreenShotOnFailure.takeScreenShot();
11             System.out.println(result.getMethod().getMethodName()+"failed, the screenshot saved in "
12                     + SCREEN_SHOT_PATH +" screenshot name: "
13                     + SCREEN_SHOT_NAME);
14         } catch (Exception e) {
15             e.printStackTrace();
16         }
17     }
18 
19     @Override
20     public void onTestStart(ITestResult result) {
21         // TODO Auto-generated method stub
22         
23     }
24 
25     @Override
26     public void onTestSuccess(ITestResult result) {
27         // TODO Auto-generated method stub
28         
29     }
30 
31     @Override
32     public void onTestSkipped(ITestResult result) {
33         // TODO Auto-generated method stub
34         
35     }
36 
37     @Override
38     public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
39         // TODO Auto-generated method stub
40         
41     }
42 
43     @Override
44     public void onStart(ITestContext context) {
45         // TODO Auto-generated method stub
46         
47     }
48 
49     @Override
50     public void onFinish(ITestContext context) {
51         // TODO Auto-generated method stub
52         
53     }
54 }

3. 在测试脚本中添加监听

  

 

 

 

以上是关于TestNG失败用例自动截图的主要内容,如果未能解决你的问题,请参考以下文章

Appium失败截图及重试机制封装

如何解决testng执行用例失败自

自动化断言失败后,测试用例还会继续执行吗

TestNG测试用例重跑详解及实践优化

TestNG测试用例重跑详解及实践优化

为什么我的'等待方法'没有使TestNG测试用例失败?