Monday, 29 June 2026

Playwright Assertions Explained with Examples in Java

Assertions are one of the most important parts of any automation framework. They help verify whether the application behaves as expected during test execution.

Playwright provides powerful built-in assertions that automatically wait for conditions to become true, making tests more stable and reliable.

In this article, we'll explore the most commonly used Playwright assertions with Java examples.


What Are Assertions?

Assertions validate the actual result against the expected result.

For example:

  • Verify page title
  • Verify element visibility
  • Verify text values
  • Verify URLs
  • Verify attributes

Without assertions, an automation script simply performs actions without confirming whether the application works correctly.


Setting Up Assertions in Playwright

Import the assertion package:

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

1. Verify Element Visibility

This is one of the most commonly used assertions.

Locator loginButton = page.locator("#loginButton");

assertThat(loginButton).isVisible();

This assertion automatically waits until the element becomes visible.


2. Verify Element Contains Text

Locator successMessage = page.locator(".success-message");

assertThat(successMessage)
        .containsText("Login Successful");

Useful for validating confirmation messages and notifications.


3. Verify Exact Text

Locator heading = page.locator("h1");

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

This checks for an exact match.


4. Verify Page Title

assertThat(page)
        .hasTitle("Amazon.in");

This is useful for verifying navigation success.


5. Verify Current URL

assertThat(page)
        .hasURL("https://www.amazon.in/");

This confirms that the user is redirected to the correct page.


6. Verify Checkbox Is Checked

Locator rememberMe = page.locator("#remember");

assertThat(rememberMe)
        .isChecked();

7. Verify Element Is Enabled

Locator submitButton = page.locator("#submit");

assertThat(submitButton)
        .isEnabled();

Useful before clicking buttons or submitting forms.


8. Verify Element Is Disabled

Locator checkoutButton = page.locator("#checkout");

assertThat(checkoutButton)
        .isDisabled();

9. Verify Input Field Value

Locator username = page.locator("#username");

assertThat(username)
        .hasValue("admin");

10. Verify Attribute Value

Locator logo = page.locator("#companyLogo");

assertThat(logo)
        .hasAttribute(
                "alt",
                "Company Logo"
        );

Why Playwright Assertions Are Better

Traditional frameworks often require explicit waits:

Thread.sleep(5000);
Assert.assertTrue(element.isDisplayed());

Playwright eliminates this problem through automatic waiting:

assertThat(locator).isVisible();

This makes tests:

  • Faster
  • More stable
  • Less flaky
  • Easier to maintain

Soft Assertions vs Hard Assertions

Playwright assertions are generally hard assertions.

If an assertion fails:

  • Test execution stops immediately.
  • Remaining steps are skipped.

This behavior helps identify failures quickly.


Best Practices

Use meaningful assertions

Good:

assertThat(loginSuccessMessage)
        .containsText("Welcome");

Avoid:

assertThat(page.locator("div"))
        .isVisible();

Validate business functionality

Assertions should verify actual business outcomes rather than implementation details.

Examples:

  • Order placed successfully
  • User logged in
  • Payment completed

Avoid unnecessary assertions

Too many assertions can make tests harder to maintain.

Focus on validating critical application behavior.


Common Assertions Cheat Sheet

AssertionPurpose
isVisible()Verify element visibility
isHidden()Verify element is hidden
hasText()Verify exact text
containsText()Verify partial text
hasValue()Verify input value
isChecked()Verify checkbox selection
isEnabled()Verify enabled state
isDisabled()Verify disabled state
hasURL()Verify page URL
hasTitle()Verify page title
hasAttribute()Verify attribute values

Conclusion

Assertions are the backbone of any automation framework.

Playwright simplifies assertions by providing built-in auto-waiting capabilities, making tests more reliable and easier to maintain.

In this article, we covered:

  • Visibility assertions
  • Text validation
  • URL verification
  • Title checks
  • Attribute validation
  • Input field assertions

Mastering these assertions will significantly improve the quality of your automation scripts and reduce flaky test failures.

In the next article, we will learn how to capture screenshots and videos in Playwright using Java.

Sunday, 28 June 2026

How to Create a Playwright Page Object Model (POM) Framework Using Java

 As automation projects grow, maintaining test scripts becomes increasingly difficult. One of the most effective ways to improve maintainability and readability is by using the Page Object Model (POM) design pattern.

In this tutorial, you'll learn how to build a Playwright Page Object Model framework using Java.


What is Page Object Model?

Page Object Model is a design pattern where each application page is represented by a separate Java class.

Instead of writing locators and actions directly in test cases, they are stored inside page classes.

This provides several benefits:

  • Better code organization
  • Improved reusability
  • Easier maintenance
  • Reduced code duplication
  • Cleaner test scripts

Project Structure

A typical Playwright POM framework structure looks like this:

src
├── main
│   └── java
│       ├── pages
│       │   ├── LoginPage.java
│       │   └── HomePage.java
│       └── utils
│
└── test
    └── java
        └── tests
            └── LoginTest.java

Step 1: Create the Login Page Class

Create a new class called LoginPage.java.

package pages;

import com.microsoft.playwright.Page;

public class LoginPage {

    private final Page page;

    public LoginPage(Page page) {
        this.page = page;
    }

    private final String usernameTextbox = "#username";
    private final String passwordTextbox = "#password";
    private final String loginButton = "#loginBtn";

    public void enterUsername(String username) {
        page.fill(usernameTextbox, username);
    }

    public void enterPassword(String password) {
        page.fill(passwordTextbox, password);
    }

    public void clickLogin() {
        page.click(loginButton);
    }

    public void login(String username, String password) {
        enterUsername(username);
        enterPassword(password);
        clickLogin();
    }
}

Step 2: Create the Home Page Class

Create a new file named HomePage.java.

package pages;

import com.microsoft.playwright.Page;

public class HomePage {

    private final Page page;

    public HomePage(Page page) {
        this.page = page;
    }

    private final String welcomeMessage = ".welcome-text";

    public String getWelcomeMessage() {
        return page.textContent(welcomeMessage);
    }
}

Step 3: Create the Test Class

Now create your test class.

package tests;

import com.microsoft.playwright.*;
import pages.HomePage;
import pages.LoginPage;

public class LoginTest {

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {

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

            Page page = browser.newPage();

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

            LoginPage loginPage = new LoginPage(page);

            loginPage.login(
                    "testuser",
                    "password123"
            );

            HomePage homePage = new HomePage(page);

            System.out.println(
                    homePage.getWelcomeMessage()
            );

            browser.close();
        }
    }
}

Step 4: Add a Base Test Class

As your framework grows, browser initialization should be moved into a separate class.

Example:

public class BaseTest {

    protected Playwright playwright;
    protected Browser browser;
    protected Page page;

    public void setup() {

        playwright = Playwright.create();

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

        page = browser.newPage();
    }

    public void tearDown() {
        browser.close();
        playwright.close();
    }
}

This prevents duplication across test classes.


Step 5: Benefits of Using POM

Using Page Object Model provides:

  • Better maintainability
  • Reusable methods
  • Cleaner test cases
  • Easier debugging
  • Improved scalability

For example, if the login button locator changes, you only update it in one place.


Best Practices for Playwright POM Framework

Use meaningful method names

Good:

loginPage.login(username, password);

Avoid:

loginPage.clickButton();

Keep locators inside page classes

Never place locators inside test classes.


Create reusable utility methods

Examples include:

  • Screenshot utilities
  • Wait utilities
  • Configuration readers
  • Test data readers

Use separate page classes for each page

Examples:

  • LoginPage
  • HomePage
  • ProductPage
  • CartPage
  • CheckoutPage

When Should You Use POM?

POM is recommended when:

  • Your project has more than a few pages
  • Multiple testers contribute to automation
  • The application changes frequently
  • Test maintenance becomes difficult

For very small projects, a simple framework may be sufficient.


Conclusion

Page Object Model is one of the most important design patterns in automation testing.

By separating page logic from test logic, your Playwright framework becomes easier to maintain, scale, and understand.

In this tutorial, you learned:

  • What POM is
  • How to create page classes
  • How to write reusable methods
  • How to organize your framework structure
  • Best practices for enterprise automation projects

In the next article, we will see about assertions.

Saturday, 27 June 2026

How to Install Playwright with Java Step by Step (2026 Beginner Guide)

Playwright has become one of the most popular automation frameworks for modern web applications. It offers fast execution, automatic waiting, multiple browser support, and excellent developer experience.

In this guide, you will learn how to install Playwright with Java from scratch and execute your first automated test.


Prerequisites

Before installing Playwright, make sure you have:

  • Java JDK 17 or higher installed
  • Maven installed and configured
  • IntelliJ IDEA or Eclipse IDE
  • Internet connection to download browser binaries

You can verify your Java installation using:

java -version

You should see output similar to:

java version "17"

Step 1: Create a Maven Project

Open your IDE and create a new Maven project.

Example project structure:

playwright-java-demo
 ├── src
 │   ├── main
 │   └── test
 ├── pom.xml

Step 2: Add Playwright Dependency

Open your pom.xml file and add the Playwright dependency.

<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.55.0</version>
    </dependency>
</dependencies>

After adding the dependency, refresh the Maven project.


Step 3: Install Browser Binaries

Playwright requires browser binaries to execute tests.

Run the following command:

mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install"

This installs:

  • Chromium
  • Firefox
  • WebKit

Step 4: Create Your First Playwright Test

Create a Java class inside the test folder.

Example:

import com.microsoft.playwright.*;

public class FirstPlaywrightTest {

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {

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

            Page page = browser.newPage();

            page.navigate("https://www.google.com");

            System.out.println(page.title());

            browser.close();
        }
    }
}

Step 5: Run the Test

Execute the class.

You should see:

  • Chromium browser launches
  • Google homepage opens
  • Page title is printed in the console
  • Browser closes automatically

Congratulations! Your first Playwright test is now running successfully.


Step 6: Understanding the Code

Playwright.create()

Creates a Playwright instance.

Playwright playwright = Playwright.create();

playwright.chromium()

Launches the Chromium browser.

Browser browser = playwright.chromium().launch();

newPage()

Creates a new browser tab.

Page page = browser.newPage();

navigate()

Opens the specified URL.

page.navigate("https://www.google.com");

Step 7: Running Tests in Headless Mode

For CI/CD pipelines, use headless mode.

.setHeadless(true)

This allows tests to execute without opening a visible browser window.


Common Installation Issues

Browser executable doesn't exist

Solution:

playwright install

Dependency download failure

Solution:

mvn clean install

Java version mismatch

Verify Java version:

java -version

Playwright works best with Java 17 or later.


Why Developers Prefer Playwright

Some advantages include:

  • Auto waiting
  • Faster execution
  • Multiple browser support
  • Network interception
  • API testing support
  • Better debugging tools

These features make Playwright an excellent choice for modern automation projects.


Conclusion

Installing Playwright with Java is straightforward and takes only a few minutes.

In this tutorial, you learned how to:

  • Create a Maven project
  • Add Playwright dependencies
  • Install browser binaries
  • Execute your first test
  • Troubleshoot common issues

In the next article, we will learn how to create a Playwright Page Object Model framework using Java.

If you're beginning your automation journey in 2026, Playwright is one of the best frameworks to invest your time in learning.

Friday, 26 June 2026

10 Playwright Features That Make It Better Than Selenium in 2026

The automation testing landscape has changed significantly over the last few years. While Selenium has been the industry standard for more than a decade, Playwright has rapidly gained popularity among automation engineers due to its modern architecture and developer-friendly features.

In this article, we'll explore 10 powerful Playwright features that make it an excellent choice for modern web automation projects in 2026.


1. Auto-Waiting Eliminates Most Synchronization Issues

One of the biggest challenges in Selenium is handling synchronization using explicit waits and implicit waits.

Playwright automatically waits for elements to become:

  • Visible
  • Enabled
  • Stable
  • Ready for interaction

This drastically reduces flaky tests and improves reliability.

Example:

page.locator("#loginButton").click();

No additional wait statements are required.


2. Built-in Support for Multiple Browsers

Playwright supports:

  • Chromium
  • Firefox
  • WebKit

This allows teams to validate applications across multiple browser engines using the same automation scripts.


3. Parallel Test Execution Out of the Box

Playwright supports parallel execution by default.

This can reduce execution times from hours to minutes for large test suites.

Example:

workers=4

With four workers, Playwright can execute four tests simultaneously.


4. Powerful Network Interception

Playwright allows testers to:

  • Mock API responses
  • Block requests
  • Modify network traffic
  • Simulate backend failures

This capability is extremely useful for testing edge cases.


5. API Testing Support

Unlike Selenium, Playwright provides native API testing capabilities.

Example:

APIRequestContext request = playwright.request().newContext();

APIResponse response = request.get("/users");

This enables UI and API automation within the same framework.


6. Trace Viewer for Debugging

Debugging failed automation tests can consume a significant amount of time.

Playwright's Trace Viewer records:

  • Screenshots
  • Network activity
  • Console logs
  • User interactions

This makes identifying failures much easier.


7. Built-in Screenshots and Video Recording

Playwright can automatically capture:

  • Screenshots
  • Videos
  • Execution traces

These artifacts are extremely valuable for failure analysis.


8. Mobile Device Emulation

Playwright supports mobile testing without additional tools.

Example devices include:

  • iPhone
  • Pixel devices
  • Tablets

This enables responsive testing directly from your automation suite.


9. Better Handling of Modern Web Applications

Modern applications heavily rely on:

  • Single Page Applications
  • Dynamic DOM updates
  • Client-side rendering

Playwright handles these scenarios more effectively due to its event-driven architecture.


10. Faster Execution Speed

Many teams report significant improvements in execution speed after migrating from Selenium to Playwright.

Faster feedback means:

  • Faster releases
  • Faster bug detection
  • Faster development cycles

Final Thoughts

Selenium remains a powerful and widely adopted automation framework. However, Playwright introduces several modern capabilities that simplify automation development and improve test stability.

If you are starting a new automation project in 2026, Playwright deserves serious consideration.

The combination of auto-waiting, API testing, network interception, and advanced debugging tools makes it one of the most exciting frameworks in the testing ecosystem today.

Are you using Selenium or Playwright for your projects? Share your experience in the comments below.

Friday, 19 June 2026

Welcome Back

 Hi Friends,


After so many days/years wanted to get back into blogging....

Lets see how it will be :)


Wednesday, 4 January 2017

JAVA integration with twitter






JAVA integration with twitter


Go to the URL https://apps.twitter.com/ and create a new application. Give access level in ‘Settings’ as ‘Read, Write and Access direct messages’. You will get both consumer key and secret.

And  go to settings and check the permissions to read write and direct messages

Get

Consumer Key

Consumer Secret

see the screen


And also generate by clicking on generate access token it will display

Access Token
Access Token Secret.


Add dependency

<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.2</version>
</dependency>

Or 
 
Else we can add jar twitter4j-core


Code:


import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class JavaTweet {

static String consumerKeyStr = "PASTE CONSUMER KEY HERE";
static String consumerSecretStr = "PASTE CONSUMER SECRET HERE";
static String accessTokenStr = "PASTE ACCESS TOKEN HERE";
static String accessTokenSecretStr = "PASTE ACCESS TOKEN SECRET HERE";

public static void main(String[] args) {

try {
Twitter twitter = new TwitterFactory().getInstance();

twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
AccessToken accessToken = new AccessToken(accessTokenStr,
accessTokenSecretStr);

twitter.setOAuthAccessToken(accessToken);

twitter.updateStatus("TWEET ON TWITTER EXAMPLE");

System.out.println("Successfully updated the status in Twitter.");
} catch (TwitterException te) {
te.printStackTrace();
}
}

}



That’s great. We have done it.
______________________________________________________________________________

We have also a neither way to tweet using java by Twitter REST API. For that we need

commons-codec-1.6.jar
  • commons-io-2.4.jar
  • commons-logging-1.1.3.jar
  • httpclient-4.3.1.jar
  • httpcore-4.3.jar
  • signpost-core-1.2.1.2.jar
  • signpost-commonshttp4-1.2.1.2.jar
All these jar files.


And code is as follows.


import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class JavaRestTweet {
static String consumerKeyStr = "PASTE CONSUMER KEY HERE";
static String consumerSecretStr = "PASTE CONSUMER SECRET HERE";
static String accessTokenStr = "PASTE ACCESS TOKEN HERE";
static String accessTokenSecretStr = "PASTE ACCESS TOKEN SECRET HERE";


public static void main(String[] args) throws Exception {
OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr,
consumerSecretStr);
oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);

HttpPost httpPost = new HttpPost(
"http://api.twitter.com/1.1/statuses/update.json?status=Hello%20Twitter%20Exammple.");

oAuthConsumer.sign(httpPost);

HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);

int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println(statusCode + ':'
+ httpResponse.getStatusLine().getReasonPhrase());
System.out.println(IOUtils.toString(httpResponse.getEntity().getContent()));

}
}


That’s great. We have done it.

Small JS to LOGIN to FB and POST on ur wall



<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Posting Job Opening To FB Wall</title>
<script type="text/javascript" src=""></script>
    </head>
    <body class="">
    <div id="fb-root" class=" fb_reset">
    <script>
var APP_ID="APP ID HERE";

window.fbAsyncInit = initFacebook;

function initFacebook()
{
    FB.init({
      appId  : APP_ID,
      status : true, // check login status
      cookie : false, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });

    FB.getLoginStatus(onFacebookLoginStatus);
};

(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
    }());
    //the login function
function facebookLogin()
{
    var loginUrl="http://www.facebook.com/dialog/oauth/?"+
        "scope=publish_actions&"+
        "client_id="+APP_ID+"&"+
        "redirect_uri="+document.location.href+"&"+
        "response_type=token";
    window.location=loginUrl;
}


//Callback function for FB.login
function onFacebookLoginStatus(response)
{
    if (response.status=="connected" && response.authResponse)
    {
        document.getElementById("txtEcho").innerHTML="Logged in.";

    }
    else
    {
        document.getElementById("txtEcho").innerHTML="Not logged in.";
    }

}


    //post to wall function
function postToWallUsingFBApi()
{
  
 FB.ui({
method: 'feed',
link: 'http://Examplesite.net/join-us/',
description:'Example description',
caption: 'Example Caption',
}, function(response){});

}

    //the return function after posting to wall
function onPostToWallCompleted(response)
{
    if (response)
    {
        if (response.error)
        {
            document.getElementById("txtEcho").innerHTML=response.error.message;
        }
        else
        {
            if (response.id)
                document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.id;
            else if (response.post_id)
                document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.post_id;
            else
                document.getElementById("txtEcho").innerHTML="Unknown Error";
        }
    }
}



    </script>
    <input id="loginButton" type="button" value="Login To Facebook" onclick="javascript:facebookLogin();">
    <input id="postToWallWithFBApiPrompt" type="button" value="Post To Wall Using FB.api"          onclick="javascript:postToWallUsingFBApi();">
    <div id="txtEcho"><b></b></div>
    </body>
    </html>