Playwright + Java · Lesson 28 of 38
Module 28: Test Lifecycle & Hooks
Your task
Implement safeCloseContext:
Write it in the editor, then press Check answer (Ctrl + Enter).
// Resource cleanup guarantee:
public void afterEachCleanup(Page page, BrowserContext context, boolean testFailed) {
if (testFailed && page != null) {
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("failures/fail.png")));
}
if (context != null) {
context.close();
}
}Managing system resources is essential for large test suites. In this lesson, you will master the test lifecycle: BeforeAll, BeforeEach, AfterEach, and AfterAll to guarantee video recordings, traces, and pages are cleanly flushed and closed. Let's master test hooks!
Part of the Playwright + Java course (Playwright with Java). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
Always wrap teardown logic in try-finally blocks or null checks so subsequent test suites aren't blocked from releasing browser resources.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___