28. Test Execution Lifecycle, Hooks & Resource Cleanup

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.
// 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();
    }
}

Task

  • Implement safeCloseContext:
  • 1. Accept BrowserContext context.
  • 2. If context != null, invoke context.close().
πŸ’‘Common doubts
Did you like the problem?
Lesson 28 of 38
Java
Loading code editor…
Next