Playwright Java take a screenshot when only test failed using Java and TestNG.

Sameera De Silva
2 min readOct 4, 2024

--

For that, we could use the below code.

package com.sam.scripts;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class ScreenShotOnFailureWithTestNg {

private Playwright playwright;
private Browser browser;
private Page page;

@BeforeMethod
public void setUp(ITestContext context) {
// We can take screenshots in headless mode too.
playwright = Playwright.create();
browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));// Set false to run in GUI
// This line creates a new page object within the browser instance. The page object represents a single web page that can be navigated, interacted with, and tested.(It's kind of tab but exactly a tab.)
page = browser.newPage();

}

@Test
public void myTest() {
// This code instructs the page object to navigate to the specified URL
page.navigate("https://the-internet.herokuapp.com/");
System.out.println(page.title());
assertThat(page).hasTitle("The Internet NOT"); // To make it fail add different word correct word is The Internet
}

@AfterMethod
public void tearDown(ITestResult result) throws IOException {
if (result.getStatus() == ITestResult.FAILURE || result.getStatus() == ITestResult.SKIP) {
// Take a screenshot of the entire page as byte format for extent report we need that.
byte[] screenshot = page.screenshot();
// Get the current working directory.
String workingDirectory = System.getProperty("user.dir");
// Create the Screenshots folder if it doesn't exist.
Path screenshotsFolder = Paths.get(workingDirectory, "Screenshots");
if (!Files.exists(screenshotsFolder)) {
Files.createDirectory(screenshotsFolder);
}
// Save the screenshot to the Screenshots folder.
Path screenshotPath = screenshotsFolder.resolve("screenshot.png");
Files.write(screenshotPath, screenshot);
}
page.close();
browser.close();
playwright.close();
}
}

This will create a screenshot in below location.

--

--

No responses yet