Showing posts with label Playwright with JUnit. Show all posts
Showing posts with label Playwright with JUnit. Show all posts

Playwright with Junit


















Complete Guide to Assertions in Playwright Java with JUnit (SEO Optimized & AdSense Friendly)

When building automated UI tests, performing actions like clicking buttons or filling forms is only half the job. The real value of automation comes from validating expected outcomes. That’s where assertions play a critical role.

In Playwright for Java, assertions help verify conditions such as whether an element is visible, enabled, contains specific text, or whether a page title matches the expected value. Without assertions, automation scripts cannot truly confirm that an application behaves correctly.

In this detailed and beginner-friendly guide, we will explore:

  • What are assertions in Playwright Java?

  • How Playwright and JUnit work together

  • Benefits of using Playwright with JUnit

  • Common assertion types in Playwright

  • Complete login page example with JUnit

  • Maven dependencies setup

  • Code explanation in detail

  • Best practices for writing stable assertions

  • Real-world testing tips

This guide is written in a human-like style, fully SEO optimized, and AdSense-friendly for educational publishing.


What Are Assertions in Playwright Java?

Assertions are validation statements used in automated tests to verify whether a condition is true.

For example:

  • Is the login button visible?

  • Does the page title contain the expected text?

  • Is an input field enabled?

  • Does an element contain specific text?

If the assertion passes, the test continues.
If it fails, the test stops and reports an error.

In Playwright for Java, assertions can be performed using:

  1. JUnit assertions

  2. TestNG assertions

  3. Playwright’s built-in Assertions class

Playwright provides a powerful assertion library under:

com.microsoft.playwright.assertions


How Playwright and JUnit Work Together

Playwright is responsible for:

  • Launching browsers

  • Navigating web pages

  • Interacting with UI elements

JUnit provides:

  • Test structure

  • Assertions

  • Lifecycle management

  • Reporting

In simple terms:

👉 Playwright performs browser automation
👉 JUnit manages and validates test execution

Each test method in JUnit represents a test scenario such as:

  • Login functionality

  • Form submission

  • Navigation verification

  • UI validation

Inside these test methods, Playwright is used to interact with the application.


Benefits of Using Playwright with JUnit

Using Playwright with JUnit offers several advantages.


(a) Organized Test Execution

JUnit allows grouping tests into classes and methods.

Example:

  • LoginTest

  • RegistrationTest

  • DashboardTest

Tests can be run:

  • Individually

  • As a suite

  • From Maven

  • From CI/CD pipeline


(b) Assertions and Validations

JUnit provides built-in assertion methods such as:

  • assertTrue()

  • assertEquals()

  • assertFalse()

  • assertNotNull()

Playwright also provides:

  • assertThat(locator).isVisible()

  • assertThat(locator).hasText()

This combination makes validation very powerful.


(c) Lifecycle Management

JUnit provides annotations such as:

  • @BeforeAll

  • @AfterAll

  • @BeforeEach

  • @AfterEach

These help manage:

  • Browser setup

  • Context initialization

  • Cleanup after execution


(d) Parallel Execution

Both Playwright and JUnit support parallel test execution, which:

  • Reduces test execution time

  • Improves efficiency

  • Helps large automation suites


(e) CI/CD Integration

JUnit generates XML/HTML reports that integrate easily with:

  • Jenkins

  • GitHub Actions

  • GitLab CI

  • Maven

  • Azure DevOps

This makes automated testing part of continuous integration.


Common Assertion Types in Playwright Java

Below are the most commonly used assertions in Playwright:

Assertion TypeMethod
Element is visibleassertThat(locator).isVisible();
Element has textassertThat(locator).hasText("value");
Element is enabledassertThat(locator).isEnabled();
Element is hiddenassertThat(locator).isHidden();
Element contains valueassertThat(locator).hasValue("value");
Title verificationpage.title() + JUnit assertion


Example: Login Page Assertion in Playwright Java

Let’s use the login page:

https://opensource-demo.orangehrmlive.com/web/index.php/auth/login

We will verify:

  • Page title

  • Username field visibility

  • Login button enabled

  • Placeholder text


Step 1: Add Maven Dependencies

Add the following dependencies in pom.xml:

<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.10.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.10.2</version> <scope>test</scope> </dependency>

Make sure you use the latest stable versions.


Step 2: Complete Playwright + JUnit Code

import com.microsoft.playwright.*; import org.junit.jupiter.api.*; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class LoginTest { static Playwright playwright; static Browser browser; static Page page; static BrowserContext context; @BeforeAll static void setup() { playwright = Playwright.create(); browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); context = browser.newContext(); page = context.newPage(); } @Test void testLoginPageAssertions() { page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login"); // Title Assertion String title = page.title(); Assertions.assertTrue(title.contains("OrangeHRM"), "Page title does not match"); // Username field visibility Locator usernameField = page.locator("input[name='username']"); assertThat(usernameField).isVisible(); // Login button enabled Locator loginButton = page.locator("button[type='submit']"); assertThat(loginButton).isEnabled(); // Placeholder verification Assertions.assertEquals("Username", usernameField.getAttribute("placeholder")); } @AfterAll static void tearDown() { context.close(); browser.close(); playwright.close(); } }


Detailed Code Explanation

Let’s understand each section clearly.


Playwright.create()

Initializes the Playwright engine.

Without this, browser automation cannot start.


browser.newContext()

Creates a fresh browser session.

Think of it as opening a new incognito window.

This ensures:

  • No cache

  • No cookies

  • Clean test environment


page.navigate()

Opens the specified URL.


Locator

Locator usernameField = page.locator("input[name='username']");

Locator identifies elements in the DOM.

Playwright uses smart waiting, meaning it automatically waits for elements to appear.


Playwright Assertion

assertThat(usernameField).isVisible();

Checks if the element is visible.

If not, the test fails immediately.


JUnit Assertion

Assertions.assertTrue(title.contains("OrangeHRM"));

Validates the page title using JUnit.


@BeforeAll and @AfterAll

These manage:

  • Setup before all tests

  • Cleanup after execution

This ensures no browser instances remain open.


Why Use Playwright Assertions Instead of Only JUnit?

Playwright assertions provide:

  • Auto-waiting

  • Retry mechanism

  • Better error messages

  • Synchronization handling

For example:

assertThat(locator).hasText("Dashboard");

This waits until text appears.

JUnit does not provide auto-waiting.


Best Practices for Writing Assertions

✔ Prefer Playwright assertions for UI elements
✔ Use JUnit assertions for non-UI values
✔ Avoid Thread.sleep()
✔ Use descriptive error messages
✔ Validate both positive and negative scenarios
✔ Always close browser in teardown


Real-World Assertion Examples

Verify Error Message

Locator errorMsg = page.locator(".error-message"); assertThat(errorMsg).hasText("Invalid credentials");


Verify URL

Assertions.assertTrue(page.url().contains("dashboard"));


Verify Element Count

assertThat(page.locator(".menu-item")).hasCount(5);


Common Mistakes in Assertions

❌ Not waiting for page load
❌ Using hard waits
❌ Verifying unstable text
❌ Using incorrect locators
❌ Ignoring dynamic behavior


Advanced Tip: Using Soft Assertions (JUnit Alternative)

If you want multiple validations in a single test without stopping execution, consider using soft assertion libraries like AssertJ.


Why Assertions Are Critical in Automation Testing

Without assertions:

  • Tests cannot validate outcomes

  • Automation loses meaning

  • Failures go unnoticed

  • CI/CD loses reliability

Assertions transform automation scripts into true test cases.


Interview Questions on Playwright Assertions

  1. What is the difference between Playwright assertion and JUnit assertion?

  2. Why is auto-wait important in UI testing?

  3. How do you verify element visibility?

  4. How do you validate dynamic text?

  5. How do you handle assertions in parallel tests?


Suggested Posts:

1. Trace Viewer in Playwright
2. File Download in Playwright
3. Comma Selectors in Playwright
4. Handle Dynamic Webtable in Playwright
5. Page Object Model in Playwright