Skip to content

Instantly share code, notes, and snippets.

@JamesZoft
Last active April 5, 2019 20:39
Show Gist options
  • Save JamesZoft/091eacc16f0623be2f84521d79c71f70 to your computer and use it in GitHub Desktop.
Save JamesZoft/091eacc16f0623be2f84521d79c71f70 to your computer and use it in GitHub Desktop.
Implementation of TestExecutionExceptionHandler that takes a screenshot of the current selenium context to be used as a Jupiter extension
import com.amazonaws.SdkClientException;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TakeScreenshotOnFailureExtension implements TestExecutionExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(TakeScreenshotOnFailureExtension.class);
private WebDriver driver;
TakeScreenshotOnFailureExtension(WebDriver driver) {
this.driver = driver;
}
@Override
public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) throws Throwable {
if ("true".equalsIgnoreCase(System.getProperty("takeScreenshotOnFailure"))) {
TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
try {
String fileUrl = new SeleniumScreenshotUploader()
.uploadSeleniumScreenshot(takesScreenshot.getScreenshotAs(OutputType.BYTES));
LOGGER.info("********** Failure screenshot **********");
LOGGER.info(fileUrl);
LOGGER.info("******************************************");
} catch (WebDriverException e) {
LOGGER.error("WebDriver error whilst trying to take screenshot", e);
} catch (UnsupportedOperationException e) {
LOGGER.error("Driver being used does not support taking screenshots", e);
} catch (SdkClientException e) {
LOGGER.error(e.getMessage(), e);
}
}
throw throwable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment