Showing posts with label #VisualTesting. Show all posts
Showing posts with label #VisualTesting. Show all posts

Monday, August 3, 2026

Playwright Browser Contexts in Java (Complete Guide)

Introduction

One of the biggest advantages of Playwright over traditional browser automation tools is its Browser Context architecture.

Instead of opening a completely new browser process for every test, Playwright creates lightweight, isolated browser contexts within the same browser instance. Each context behaves like a brand-new browser profile with its own cookies, local storage, session storage, cache, and permissions.

This approach makes tests faster, more reliable, and ideal for parallel execution.

In this guide, you'll learn how Browser Contexts work, why they're important, and how to use them effectively in Playwright with Java.


What is a Browser Context?

A Browser Context is an isolated browser session.

Each context has its own:

  • Cookies
  • Local Storage
  • Session Storage
  • Permissions
  • Cache
  • Authentication State

Think of a Browser Context as an "Incognito Window" inside the browser.

Each context is completely independent of the others.


Browser vs Browser Context

Many beginners confuse these concepts.

BrowserBrowser Context
Browser processIsolated browser session
HeavyweightLightweight
Can contain multiple contextsContains one or more pages
Shared executableSeparate storage and cookies

Typically, you launch one browser and create multiple browser contexts.


Creating a Browser Context

Example:

Playwright playwright = Playwright.create();

Browser browser =
    playwright.chromium().launch(
        new BrowserType.LaunchOptions()
            .setHeadless(false)
    );

BrowserContext context =
    browser.newContext();

Page page = context.newPage();

page.navigate("https://example.com");

This creates a new isolated session.


Creating Multiple Browser Contexts

You can create multiple independent users inside the same browser.

BrowserContext adminContext =
    browser.newContext();

BrowserContext customerContext =
    browser.newContext();

Page adminPage =
    adminContext.newPage();

Page customerPage =
    customerContext.newPage();

The two users do not share any data.


Why Browser Contexts Matter

Without Browser Contexts:

  • Sessions interfere with each other.
  • Cookies are shared.
  • Authentication conflicts occur.
  • Parallel execution becomes unreliable.

Browser Contexts solve these problems by providing complete isolation.


Cookie Isolation

Suppose User A logs into an application.

Their cookies remain inside their Browser Context.

User B opens another Browser Context.

User B starts with a completely clean session.

No cookies are shared.

This behaviour makes parallel testing reliable.


Local Storage Isolation

Local Storage is also isolated.

Example:

Context A

theme = dark

Context B

theme = light

Each context maintains its own storage.


Session Storage Isolation

Session Storage exists only within its Browser Context.

Closing the context removes all session data.

This closely matches real browser behaviour.


Reusing Authentication

Instead of logging in repeatedly, save the authenticated state.

context.storageState(
    new BrowserContext.StorageStateOptions()
        .setPath(Paths.get("storageState.json"))
);

Later, create a new context using the saved authentication.

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setStorageStatePath(
                Paths.get("storageState.json")
            )
    );

This significantly reduces test execution time.


Multi-User Testing

Many enterprise applications involve interactions between multiple users.

Example:

  • Administrator approves a request.
  • Manager reviews the request.
  • Employee views the approved status.

Each user can run in a separate Browser Context.

BrowserContext admin =
    browser.newContext();

BrowserContext manager =
    browser.newContext();

BrowserContext employee =
    browser.newContext();

This allows realistic end-to-end workflow testing.


Parallel Execution

Browser Contexts are lightweight and well suited for parallel testing.

Benefits include:

  • Faster execution
  • Better resource utilization
  • Independent sessions
  • Reduced setup time

Closing Browser Contexts

Always close contexts after execution.

context.close();

Finally, close the browser.

browser.close();

Proper cleanup prevents resource leaks.


Browser Context Options

When creating a context, you can configure:

  • Viewport size
  • Locale
  • Time zone
  • Geolocation
  • Permissions
  • HTTP credentials
  • Color scheme
  • User agent

Example:

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setViewportSize(1366, 768)
            .setLocale("en-US")
            .setTimezoneId("Asia/Kolkata")
    );

This makes testing different environments simple.


Real-World Enterprise Example

Consider an e-commerce platform.

Scenario:

  1. Customer places an order.
  2. Warehouse user processes the order.
  3. Administrator verifies the shipment.

Each role runs in its own Browser Context.

All three users interact with the same application simultaneously without affecting one another.


Common Mistakes

Reusing the Same Context for Every Test

This can cause cookies and session data to leak between tests.

Create a fresh Browser Context whenever practical.


Forgetting to Close Contexts

Unused contexts consume memory.

Always close them after the test finishes.


Sharing Authentication Across Unrelated Tests

Keep authentication states separate unless sharing is intentional.

This improves test independence.


Best Practices

Create One Context Per Test

This ensures isolation and reduces flaky tests.


Save Authentication State

Reuse authenticated sessions for faster execution.


Keep Tests Independent

Avoid dependencies between contexts or test cases.


Use Contexts for Parallel Users

Model real-world workflows with separate contexts for different user roles.


Clean Up Resources

Always close pages, contexts, and browsers when execution completes.


Common Interview Questions

What is a Browser Context?

A Browser Context is an isolated browser session with its own cookies, storage, cache, and permissions.


Why are Browser Contexts important?

They allow isolated sessions, faster execution, reliable parallel testing, and multi-user automation.


Are Browser Contexts the same as browser windows?

No. Multiple Browser Contexts can exist within a single browser process, each behaving like an independent browser profile.


Can Browser Contexts share cookies?

No. Cookies are isolated unless explicitly imported or exported.


Why is Playwright faster than launching multiple browsers?

Creating Browser Contexts is significantly lighter than starting separate browser processes, reducing execution time and resource usage.


Conclusion

Browser Contexts are one of Playwright's most powerful features and the foundation of scalable automation frameworks.

They provide secure session isolation, simplify multi-user testing, improve parallel execution, and reduce overall test runtime.

In this guide, you learned how to:

  • Understand Browser Context architecture
  • Create isolated browser sessions
  • Manage cookies and storage
  • Reuse authentication state
  • Test multiple users simultaneously
  • Configure context options
  • Apply enterprise best practices

Mastering Browser Contexts will help you build faster, cleaner, and more reliable Playwright automation frameworks suitable for enterprise-scale applications.

Thursday, July 30, 2026

Playwright Mobile & Device Emulation Using Java (Complete Guide)

Introduction

Today, users access applications from desktops, laptops, tablets, and smartphones with different screen sizes and operating systems. A page that looks perfect on a desktop can become unusable on a mobile device if responsive design is not implemented correctly.

Testing every physical device is expensive and time-consuming. Playwright solves this challenge through powerful device emulation, allowing automation engineers to simulate mobile devices directly within the browser.

In this guide, you'll learn how to configure mobile testing, emulate devices, validate responsive layouts, and apply enterprise best practices using Playwright with Java.


What is Device Emulation?

Device emulation simulates the behaviour of a mobile or tablet device inside the browser.

Playwright can emulate:

  • Screen resolution
  • Viewport size
  • Touch interactions
  • Mobile user agent
  • Device scale factor
  • Orientation

This enables responsive UI testing without requiring physical devices.


Why Mobile Testing Matters

Mobile users now account for a significant portion of web traffic.

Common issues found during mobile testing include:

  • Overlapping text
  • Hidden buttons
  • Broken navigation menus
  • Horizontal scrolling
  • Incorrect font sizes
  • Touch targets that are too small

Automated mobile testing helps detect these problems early.


Creating a Mobile Browser Context

Create a browser context with a mobile-sized viewport.

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setViewportSize(390, 844)
            .setIsMobile(true)
            .setHasTouch(true)
    );

Page page = context.newPage();

This creates a browser session that behaves like a mobile device.


Setting a Custom Viewport

Different applications may require testing with specific screen sizes.

Example:

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setViewportSize(768, 1024)
    );

Common viewport sizes:

DeviceResolution
iPhone 14390 × 844
Pixel 7412 × 915
iPad768 × 1024
Desktop1920 × 1080

Emulating Touch Support

Touch gestures behave differently from mouse clicks.

Enable touch support:

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setHasTouch(true)
            .setIsMobile(true)
    );

This allows Playwright to simulate touch-based interactions.


Emulating Screen Orientation

Applications should work in both portrait and landscape modes.

Portrait example:

.setViewportSize(390, 844)

Landscape example:

.setViewportSize(844, 390)

Testing both orientations helps identify layout issues.


Responsive Navigation Testing

Many applications replace the desktop navigation bar with a hamburger menu.

Example:

page.locator(".menu-icon").click();

page.getByRole(
        AriaRole.LINK,
        new Page.GetByRoleOptions()
            .setName("Products"))
    .click();

Always verify that mobile navigation remains usable.


Validating Responsive Layout

Use assertions to confirm that important elements remain visible.

assertThat(
    page.locator("#checkoutButton")
).isVisible();

This ensures essential functionality is available on smaller screens.


Capturing Mobile Screenshots

Screenshots are useful for responsive regression testing.

page.screenshot(
    new Page.ScreenshotOptions()
        .setPath(Paths.get("screenshots/mobile-homepage.png"))
);

Store screenshots as part of your regression suite.


Testing Different User Agents

Some websites display different content based on the browser's user agent.

Example:

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setUserAgent(
                "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)"
            )
    );

This helps validate device-specific behaviour.


Combining Device Emulation with Geolocation

Many mobile applications use location services.

Example:

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setGeolocation(12.9716, 77.5946)
            .setPermissions(List.of("geolocation"))
    );

This allows testing of location-aware features.


Testing Mobile Forms

Mobile keyboards and screen sizes can expose usability issues.

Verify:

  • Input fields remain visible.
  • Labels are readable.
  • Buttons are easy to tap.
  • Validation messages display correctly.

Organising Mobile Test Suites

Recommended project structure:

src

└── test

    ├── desktop

    ├── mobile

    └── tablet

This separation improves maintainability.


Best Practices

Test Multiple Viewports

Do not assume one mobile resolution is sufficient.

Include:

  • Small phones
  • Large phones
  • Tablets
  • Desktop

Avoid Pixel-Perfect Assertions

Minor rendering differences are normal.

Validate behaviour and layout rather than exact pixel positions.


Use Accessible Locators

Prefer:

  • getByRole()
  • getByLabel()
  • getByPlaceholder()
  • getByTestId()

These are more stable than long CSS selectors.


Combine with Visual Testing

Capture screenshots on different devices to detect responsive regressions.


Execute in CI/CD

Run mobile tests alongside desktop tests in Jenkins, GitHub Actions, or Azure DevOps to ensure consistent quality across devices.


Common Challenges

Hidden Elements

Some controls appear only on mobile.

Ensure your tests account for responsive UI changes.


Sticky Headers

Sticky navigation bars may hide content during scrolling.

Validate scrolling behaviour carefully.


Touch vs Mouse

Touch interactions can differ from desktop mouse behaviour.

Always enable touch when testing mobile-specific features.


Slow Mobile Networks

Consider combining device emulation with network throttling to evaluate application performance under slower connections.


Real-World Enterprise Example

An online banking application works correctly on desktop.

However, on mobile:

  • The Transfer Funds button is pushed below the visible area.
  • Customers cannot complete transfers without scrolling unexpectedly.

A Playwright mobile test detects the issue before release, preventing customer frustration and production defects.


Common Interview Questions

What is device emulation in Playwright?

Device emulation simulates a mobile or tablet environment by configuring viewport size, touch support, user agent, and other device characteristics.


Does Playwright require physical devices?

No. Most responsive testing can be performed using Playwright's browser-based emulation. Physical devices are still valuable for final validation.


Why enable hasTouch?

It allows Playwright to simulate touch interactions that behave differently from mouse events.


Can Playwright test responsive layouts?

Yes. By changing viewport sizes and validating element visibility, Playwright can verify responsive behaviour across different screen sizes.


Should mobile tests replace desktop tests?

No. Both desktop and mobile experiences should be validated because users access applications from multiple device types.


Conclusion

Responsive design is essential for modern web applications, and Playwright provides an efficient way to automate mobile and tablet testing without relying on physical hardware.

In this guide, you learned how to:

  • Configure mobile browser contexts
  • Set custom viewports
  • Enable touch support
  • Test portrait and landscape orientations
  • Validate responsive layouts
  • Capture mobile screenshots
  • Test with custom user agents
  • Combine mobile testing with geolocation
  • Apply enterprise best practices

By incorporating device emulation into your automation framework, you'll improve application quality across desktops, tablets, and smartphones while reducing the cost and complexity of cross-device testing.

Tuesday, July 28, 2026

Playwright Visual Testing Using Java (Screenshot Comparison & UI Regression Testing)

Introduction

Functional testing verifies whether an application behaves correctly, but it cannot detect visual issues such as broken layouts, overlapping text, incorrect colours, missing icons, or unexpected UI changes.

Visual Testing addresses this gap by comparing screenshots of the application against previously approved baseline images. If any unexpected visual differences are detected, the test fails, helping teams identify UI regressions before they reach production.

Playwright includes built-in support for screenshot capture and comparison, making visual regression testing simple and reliable.

In this guide, you'll learn how to implement visual testing using Playwright with Java.


What is Visual Testing?

Visual Testing is the process of comparing the current appearance of an application with a known baseline image.

Instead of validating only HTML elements, visual testing verifies:

  • Layout
  • Colours
  • Fonts
  • Images
  • Buttons
  • Icons
  • Spacing
  • Alignment
  • Responsive design

Why Visual Testing is Important

Visual bugs often escape traditional automation because the page is technically functional.

Examples include:

  • Button shifted outside the screen
  • Text overlapping an image
  • Missing company logo
  • Incorrect font size
  • Broken navigation menu
  • Hidden labels
  • Responsive layout issues

Visual testing helps detect these problems automatically.


When Should You Use Visual Testing?

Visual testing is particularly useful for:

  • Home pages
  • Dashboards
  • Checkout pages
  • Reports
  • Responsive layouts
  • Marketing pages
  • Admin portals

Avoid relying solely on visual tests for pages with highly dynamic content unless that content can be controlled.


Types of Screenshots in Playwright

Playwright supports several screenshot strategies.

Page Screenshot

Capture the visible portion of the page.

page.screenshot(
    new Page.ScreenshotOptions()
        .setPath(Paths.get("screenshots/homepage.png"))
);

Full Page Screenshot

Capture the entire page, including content below the fold.

page.screenshot(
    new Page.ScreenshotOptions()
        .setFullPage(true)
        .setPath(Paths.get("screenshots/fullpage.png"))
);

This is ideal for validating long pages.


Element Screenshot

Capture only a specific component.

page.locator("#loginForm")
    .screenshot(
        new Locator.ScreenshotOptions()
            .setPath(Paths.get("screenshots/loginForm.png"))
    );

This reduces maintenance because only the target component is compared.


Creating Baseline Images

The first successful execution establishes the approved UI.

Example:

baseline/

├── homepage.png

├── login.png

├── dashboard.png

Future executions compare the latest screenshots against these baseline images.


Comparing Screenshots

Typical visual testing workflow:

  1. Capture the current screenshot.
  2. Load the baseline image.
  3. Compare both images.
  4. Generate a difference image if changes exist.
  5. Fail the test when differences exceed the accepted threshold.

Handling Dynamic Content

Some page elements change every time.

Examples:

  • Current date
  • Current time
  • Advertisements
  • User avatars
  • Rotating banners
  • Notifications

These should not cause test failures.


Mask Dynamic Elements

Mask unstable regions before capturing screenshots.

Example:

page.locator(".notification")
    .screenshot(
        new Locator.ScreenshotOptions()
            .setMask(List.of(page.locator(".timestamp")))
            .setPath(Paths.get("screenshots/notification.png"))
    );

This helps eliminate false positives.


Responsive UI Testing

Validate multiple viewport sizes.

Example:

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setViewportSize(390, 844)
    );

Capture screenshots for:

  • Mobile
  • Tablet
  • Desktop

This ensures the application renders correctly across devices.


Organising Screenshot Files

Recommended project structure:

src

└── test

    ├── baseline

    ├── actual

    ├── diff

    └── reports

Keeping these directories separate makes reviewing results easier.


Running Visual Tests in CI/CD

Visual regression testing integrates well with:

  • Jenkins
  • GitHub Actions
  • Azure DevOps
  • GitLab CI

Typical workflow:

  1. Build application.
  2. Execute Playwright tests.
  3. Capture screenshots.
  4. Compare against baseline.
  5. Publish reports.
  6. Fail the build if unexpected visual changes are detected.

Best Practices

Use Stable Test Data

Ensure the application displays predictable data before taking screenshots.


Test Individual Components

Prefer component-level screenshots over full-page screenshots where possible.

Component comparisons are faster and easier to maintain.


Control Browser Environment

Keep the following consistent:

  • Browser version
  • Viewport size
  • Font availability
  • Operating system
  • Zoom level

Consistency reduces false failures.


Review Baseline Changes Carefully

Update baseline images only when UI changes are intentional and approved.

Treat baseline updates as part of your code review process.


Avoid Visual Tests for Highly Dynamic Pages

Pages with constantly changing content may require masking or alternative validation strategies.


Common Challenges

Different Fonts

Missing fonts can cause text rendering differences.

Install the same fonts across all environments.


Animation Effects

Animations can produce inconsistent screenshots.

Disable animations during testing whenever possible.


Dynamic Advertisements

Mask or disable advertisement sections to improve stability.


Browser Differences

Small rendering differences may exist between Chromium, Firefox and WebKit.

Maintain separate baselines if cross-browser visual validation is required.


Common Interview Questions

What is visual regression testing?

Visual regression testing compares the current appearance of an application with a baseline image to detect unintended UI changes.


Why can't functional tests detect visual bugs?

Functional tests verify behaviour, not appearance. They may pass even when the UI layout is broken.


What is a baseline image?

A baseline image is the approved screenshot used as the reference for future comparisons.


How do you handle dynamic elements in visual testing?

Mask dynamic regions, use stable test data, or exclude changing content from comparisons.


Should visual testing replace functional testing?

No. Visual testing complements functional automation by validating appearance, while functional tests verify business behaviour.


Real-World Enterprise Example

Imagine an online shopping application.

After a CSS update:

  • The Add to Cart button becomes partially hidden.
  • Functional automation still clicks the button successfully.
  • Customers on smaller screens cannot see the button.

A visual regression test immediately highlights the layout difference, allowing the issue to be fixed before release.


Conclusion

Visual testing is an essential addition to any modern automation framework.

Playwright's screenshot capabilities make it easy to detect unintended UI changes, improve application quality, and reduce production defects.

In this guide, you learned how to:

  • Capture page, full-page, and element screenshots
  • Create and maintain baseline images
  • Compare screenshots
  • Handle dynamic content
  • Test responsive layouts
  • Integrate visual testing into CI/CD
  • Apply enterprise best practices

By incorporating visual regression testing into your Playwright framework, you'll catch UI issues that traditional functional tests often miss, delivering a more polished and reliable user experience.