I trying to attach a screenshot to the index.html or emailable_report.html if a test failed. I found a workable solution, but I would like to disassemble it into smaller parts so that I can use it elsewhere.
However, when I disassemble it into small parts, although it takes the picture, it does not attach it to the report.
This one works for me perfectly:
public static void insertScreenshotToReportByTestResult2(WebDriver driver, ITestResult result){
if(result.getStatus() == ITestResult.FAILURE) {
Reporter.setCurrentTestResult(result);
String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String screenshotName = result.getTestClass().getRealClass().getSimpleName() + "_" +
result.getName() + "_" + new SimpleDateFormat("HHmmss").format(new Date(result.getStartMillis()));
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(source, new File("target/screenshots/" + date + "/" + screenshotName + ".png"));
String embedImageBase64 = Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(source));
Reporter.log("<img alt='Test execution failed' src='data:image/png;base64," + embedImageBase64 + "' width='1280' height='720'/>");
} catch (IOException e) {
throw new RuntimeException("Failed to create screenshot and embed into report of failed execution.", e);
}
}
This is the disassembled version that does not work perfectly:
public static void insertScreenshotToReportByTestResult(WebDriver driver, ITestResult result){
if (result.getStatus() == ITestResult.FAILURE){
attachScreenshotToReport(takeScreenshot(driver, result.getMethod().getMethodName()));
}
}
public static File takeScreenshot(WebDriver driver, String testName){
String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String screenshotName = testName + "_" + date;
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(source, new File("target/screenshots/" + date + "/" + screenshotName + ".png"));
} catch (IOException e) {
throw new RuntimeException("Failed to create screenshot or failed save to target/screenshots.", e);
}
return source;
}
public static void attachScreenshotToReport(File source){
try {
String embedImageBase64 = Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(source));
Reporter.log("<img alt='Test execution failed' src='data:image/png;base64," + embedImageBase64 + "' width='1280' height='720'/>");
} catch (IOException e) {
throw new RuntimeException("Failed to attach screenshot to the report ", e);
}
}