02
Apr

Capture screenshot with IHookable implementation

Step 1: Implement IHookable interface to capture screenshot:
————————————————————

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;

public class BaseTest implements IHookable {

@Override
public void run(IHookCallBack callBack, ITestResult testResult) {

callBack.runTestMethod(testResult);
if (testResult.getThrowable() != null) {
try {

final Throwable testResultThrowable = testResult.getThrowable();
String message = testResultThrowable.getMessage() != null ? testResultThrowable.getMessage()
: testResultThrowable.getCause().getMessage();

if (message == null) {
message = “Test failed”;
}

Robot r = new Robot();

// It saves screenshot to desired path
String path = “C:\\xxx\\xxx\\Shot.jpg”; <== location of Screenshot // Used to get ScreenSize and capture image Rectangle capture = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage Image = r.createScreenCapture(capture); ImageIO.write(Image, "jpg", new File(path)); System.out.println("Screenshot saved"); } catch(AWTException | IOException ex) { System.out.println(ex); } } } } Step 2: Your TestNG script: --------------------------- import java.io.IOException; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(BaseTest.class) public class TestNGScript { @Test public void myFunction() throws IOException { System.out.println("Hello World"); throw new IOException(); } } output: screenshot is captured at defined location.