参考: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. 在测试脚本中添加监听