Monday, January 10, 2022

Taking screenshots for soft asserts

 

it is advisable to take screenshots of failed test cases for further analysis and proof of failure.

 public class CustomSoftAssert extends SoftAssert {
 

private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";


    @Override
    public void onAssertFailure(IAssert<?> assertCommand, AssertionError ex) {
        try {
            WebDriver driver = TestBase.getDriver();
         
            // Take screenshot
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S");
            String currentTimeInstance = formatter.format(date);
            String screenshotPath = System.getProperty("user.dir")+"/Screenshots"+ "-(" + currentTimeInstance
                    + ").jpg";
         
            File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            FileUtils.copyFile(scrFile, new File(screenshotPath));


            // To add screenshot to ReportNG HTML report as a link
            System.setProperty(ESCAPE_PROPERTY, "false");
            Reporter.log("<a href=\"" + screenshotPath + "\">Screenshot</a>");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}