Writing Your First Playwright Test in Java

Hands-on tutorial to write your first test case using Playwright with Java.

This entry is part 4 of 4 in the series Playwright With Java

Now that Playwright is set up, let’s write a simple test.

Example: Verify Page Title

import com.microsoft.playwright.*;
import org.testng.Assert;
import org.testng.annotations.*;

public class FirstPlaywrightTest {
    Playwright playwright;
    Browser browser;
    Page page;

    @BeforeClass
    public void setup() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
        page = browser.newPage();
    }

    @Test
    public void verifyTitle() {
        page.navigate("https://example.com");
        String title = page.title();
        System.out.println("Page title is: " + title);
        Assert.assertEquals(title, "Example Domain");
    }

    @AfterClass
    public void teardown() {
        browser.close();
        playwright.close();
    }
}

✅ Explanation

  • @BeforeClass → Start Playwright + Browser
  • @Test → Navigate & assert
  • @AfterClass → Close browser

Output

  • Browser launches
  • Navigates to https://example.com
  • Test passes ✅

👉 You just wrote your first Playwright test in Java with TestNG. From here, we’ll move towards page object models, parallel execution, and framework design.

Series Navigation<< Playwright Architecture & Features Every Tester Must Know

Leave a Reply

Your email address will not be published. Required fields are marked *