Playwright + Java · Lesson 27 of 38

0/38 done

Module 27: Playwright Fixtures & Reusable Setup

27. Reusable Test Fixtures & Base Test Isolation

16 minlesson

Your task

Implement createContextAndPage:

  1. Accept Browser browser.
  2. Create new context using browser.newContext().
  3. Return context.newPage().

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

BaseTest Lifecycle Fixture Pattern

java
public class BaseTest {
    protected static Playwright playwright;
    protected static Browser browser;
    protected BrowserContext context;
    protected Page page;

    public void initSuite() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch();
    }

    public void initTest() {
        context = browser.newContext();
        page = context.newPage();
    }

    public void cleanupTest() {
        if (context != null) context.close();
    }

    public void cleanupSuite() {
        if (browser != null) browser.close();
        if (playwright != null) playwright.close();
    }
}

Key Takeaways & Walkthrough Summary

Every test requires a fresh, isolated browser environment. In this lesson, we build a reusable BaseTest fixture class that automatically manages Playwright, Browser, and Context lifecycles so each test runs in total isolation. Let's build reusable test fixtures!

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

Why close context instead of browser after each test?

Closing and creating a context takes only 20-30 milliseconds, preserving test speed while guaranteeing complete isolation (cookies and storage reset).

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip