Playwright + Java · Lesson 28 of 38

0/38 done

Module 28: Test Lifecycle & Hooks

28. Test Execution Lifecycle, Hooks & Resource Cleanup

15 minlesson

Your task

Implement safeCloseContext:

  1. Accept BrowserContext context.
  2. If context != null, invoke context.close().

Write it in the editor, then press Check answer (Ctrl + Enter).

Lifecycle Hooks in Automation

  • Before All: Launch Playwright and Browser once per suite.
  • Before Each: Create a fresh BrowserContext and Page.
  • After Each: Capture failure screenshot / trace, then close context.
  • After All: Close Browser and Playwright process.
java
// 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();
    }
}

Key Takeaways & Walkthrough Summary

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.

Common Doubts & Lesson Q&A

What happens if a test crashes inside a hook?

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.

Java
Skip