Last active
May 15, 2018 01:35
-
-
Save python012/d962d797fa57a3e893d5be14b87de1b9 to your computer and use it in GitHub Desktop.
A JUnit TestWatcher to take screenshot when test fails.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ibm.robot.web.testrules; | |
import java.io.File; | |
import java.io.IOException; | |
import org.apache.commons.io.FileUtils; | |
import org.junit.rules.TestWatcher; | |
import org.junit.runner.Description; | |
import org.openqa.selenium.OutputType; | |
import org.openqa.selenium.TakesScreenshot; | |
import org.openqa.selenium.WebDriver; | |
public class ScreenshotRule extends TestWatcher { | |
private WebDriver driver = null; | |
public ScreenshotRule(WebDriver driver) { | |
this.driver = driver; | |
} | |
@Override | |
protected void failed(final Throwable e, final Description description) { | |
String userDir = System.getProperty("user.dir"); | |
String baseDir = userDir + "/failed-screenshots/" | |
+ description.getClassName() + "/"; | |
String screenshotName = description.getClassName() + "." | |
+ description.getMethodName() + ".png"; | |
File screen = null; | |
screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); | |
try { | |
File dir = new File(baseDir); | |
if(!dir.exists()) FileUtils.forceMkdir(dir); | |
File localFile = new File(baseDir + screenshotName); | |
FileUtils.copyFile(screen, localFile); | |
// Work with JUnit Attachments plugin to attach the files | |
// produced by Junit to Jenkins | |
System.out.println("[[ATTACHMENT|" + baseDir + screenshotName + "]]"); | |
} catch (IOException ioe) { | |
ioe.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working with JUnit attachment plugin,
System.out.println("[[ATTACHMENT|" + baseDir + screenshotName + "]]");
will help Jenkins to collect the screenshot as JUnit attachment.