Playwright Dotnet Page Object Model: Step-by-Step Guide (2026) | TechSarvam

Introduction to Playwright .NET Page Object Model

Test automation is an important part of modern QA engineering. As web applications become more complex, maintaining automated test scripts becomes challenging. Writing all locators, browser interactions, and validation logic inside a single test class can create duplicate code and make test maintenance difficult.

The Playwright Dotnet Page Object Model provides a structured approach to building maintainable and reusable test automation frameworks using C#, .NET, and Microsoft Playwright.

Page Object Model (POM) is a design pattern in which every application page is represented by a separate C# class. These classes contain page locators and reusable methods for performing actions such as clicking buttons, entering text, submitting forms, and navigating between pages.

In this tutorial, we will build a practical Playwright .NET Page Object Model framework using C# and NUnit. You will learn how to create a project, install dependencies, implement page classes, write reusable methods, execute tests, and handle common automation errors.

By the end, you will understand how to use Playwright Dotnet Page Object Model for beginners and how to apply it in real-world QA automation projects.

1. What Is the Page Object Model in Playwright .NET?

Page Object Model is a test automation design pattern that separates application page interactions from test execution logic.

Instead of writing locators and browser actions repeatedly in every test, we create separate classes for application pages.

For example, consider an application with the following pages:

  • Login Page
  • Home Page
  • Dashboard Page
  • Registration Page
  • Checkout Page

Each page has its own C# class containing locators and reusable methods.

Example without POM:

await page.GotoAsync(“https://www.saucedemo.com/”);

await page.Locator(“#user-name”)

    .FillAsync(“standard_user”);

await page.Locator(“#password”)

    .FillAsync(“secret_sauce”);

await page.Locator(“#login-button”)

    .ClickAsync();

If multiple tests require login functionality, the same code must be repeated.

Example with POM:

LoginPage loginPage = new LoginPage(Page);

await loginPage.NavigateAsync();

await loginPage.LoginAsync(

    “standard_user”,

    “secret_sauce”

);

Here, the login implementation is maintained inside the LoginPage class.

The test class only calls reusable methods.

Playwright page objects wrap an IPage instance and provide a higher-level interface for interacting with the application.

2. Benefits of Using POM in Test Automation

Using the Playwright .NET Page Object Model provides several advantages.

1. Code Reusability

Common application actions can be implemented once and reused across multiple test cases.

For example, the LoginAsync() method can be used in login, dashboard, profile, and checkout tests.

2. Easy Maintenance

Suppose the login button locator changes from #login-button to another selector.

Without POM, you may need to update multiple test scripts.

With POM, you can update the locator in one class.

3. Better Readability

POM makes test scripts easier to understand.

Instead of writing multiple browser interaction commands, testers can use meaningful methods such as:

await loginPage.LoginAsync(username, password);

4. Improved Regression Testing

Reusable page classes help teams maintain larger regression test suites.

When application functionality changes, developers can update the relevant page object without modifying every test case.

5. Scalability

You can create separate page classes, utility classes, test data classes, and configuration files as your framework grows.

This structure is useful for enterprise-level test automation projects.

3. Prerequisites and Environment Setup

Before creating a Playwright .NET Page Object Model project, make sure you have the following tools installed.

RequirementPurpose
.NET SDKBuild and execute C# projects
Visual Studio or VS CodeWrite C# automation scripts
Microsoft.PlaywrightBrowser automation
NUnitTest execution
PowerShellPlaywright browser installation
ChromiumBrowser execution

You can download the .NET SDK from the official Microsoft website.

Official resources:

Verify the .NET installation:

dotnet –version

If the command returns a version number, your .NET environment is ready.

4. Creating a Playwright .NET Project

Now let’s create a Playwright automation project using NUnit.

Open the terminal or PowerShell and execute:

Step 1: Create an NUnit project

dotnet new nunit -n PlaywrightPOM

Step 2: Navigate to the project directory

cd PlaywrightPOM

Step 3: Install Microsoft Playwright NUnit

dotnet add package Microsoft.Playwright.NUnit

This package provides Playwright integration with NUnit and the PageTest base class.

Step 4: Build the project

dotnet build

Building the project generates the Playwright installation script.

Step 5: Install Playwright browsers

For a project targeting .NET 8, execute:

pwsh bin/Debug/net8.0/playwright.ps1 install

This installs the required browser binaries.

If you use a different target framework, replace net8.0 with your actual target framework folder.

You can install only Chromium using:

pwsh bin/Debug/net8.0/playwright.ps1 install chromium

Your basic Playwright .NET environment is now ready.

5. Understanding the POM Project Structure

A clean folder structure makes the automation framework easier to maintain.

Create the following folders inside your project:

PlaywrightPOM

│

├── Pages

│   ├── LoginPage.cs

│   ├── HomePage.cs

│   └── DashboardPage.cs

│

├── Tests

│   ├── LoginTests.cs

│   └── DashboardTests.cs

│

├── Utilities

│   └── TestData.cs

│

├── UnitTest1.cs

│

└── PlaywrightPOM.csproj

Pages: Contains page classes, locators, and reusable application methods.

Tests: Contains NUnit test classes and validation logic.

Utilities: Contains reusable test data and helper functionality.

PlaywrightPOM.csproj: Contains project configuration and package dependencies.

This separation keeps the framework organized and supports future expansion.

6. Step-by-Step Page Object Model Implementation

Let’s implement a practical login automation example using the SauceDemo website.

Website: https://www.saucedemo.com/

We will automate the following workflow:

  1. Open the login page.
  2. Enter the username.
  3. Enter the password.
  4. Click the login button.
  5. Navigate to the products page.
  6. Validate successful login.

Step 1: Create the LoginPage class

Inside the Pages folder, create a file named LoginPage.cs.

This class will contain all login-related locators and methods.

LoginPage.cs

using Microsoft.Playwright;

using System.Threading.Tasks;

namespace PlaywrightPOM.Pages

{

    public class LoginPage

    {

        private readonly IPage _page;

        private readonly ILocator _username;

        private readonly ILocator _password;

        private readonly ILocator _loginButton;

        public LoginPage(IPage page)

        {

            _page = page;

            _username = _page.Locator(“#user-name”);

            _password = _page.Locator(“#password”);

            _loginButton = _page.Locator(“#login-button”);

        }

        public async Task NavigateAsync()

        {

            await _page.GotoAsync(

                “https://www.saucedemo.com/”

            );

        }

        public async Task LoginAsync(

            string username,

            string password)

        {

            await _username.FillAsync(username);

            await _password.FillAsync(password);

            await _loginButton.ClickAsync();

        }

    }

}

Understanding the implementation:

  • IPage: Represents a browser tab and provides methods to interact with the web page.
  • _page: Stores the IPage instance.
  • ILocator: Represents an element on the application page.
  • LoginPage(): Constructor that receives the IPage instance.
  • NavigateAsync(): Opens the application login page.
  • LoginAsync(): Accepts username and password and performs the login operation.

The constructor is important because it initializes the page object with the browser page created by Playwright.

Locators are declared once and reused whenever login functionality is required.

Notice that we are using async and await because Playwright browser operations are asynchronous.

Step 2: Create a HomePage class

After successful login, SauceDemo displays the products page.

Create another class inside the Pages folder.

HomePage.cs

using Microsoft.Playwright;

namespace PlaywrightPOM.Pages

{

    public class HomePage

    {

        private readonly IPage _page;

        private readonly ILocator _pageTitle;

        public HomePage(IPage page)

        {

            _page = page;

            _pageTitle = _page.Locator(“.title”);

        }

        public async Task<string> GetPageTitleAsync()

        {

            return await _pageTitle.InnerTextAsync();

        }

    }

}

The HomePage class contains the products page title locator.

The GetPageTitleAsync() method retrieves the title so the test class can validate successful navigation.

Step 3: Create reusable test data

Inside the Utilities folder, create TestData.cs.

namespace PlaywrightPOM.Utilities

{

    public static class TestData

    {

        public const string Username = “standard_user”;

        public const string Password = “secret_sauce”;

    }

}

Keeping test data separate makes it easier to manage credentials and test scenarios.

For real projects, credentials should be stored securely rather than committed to source control.

7. Creating the NUnit Test Class

Now let’s create the actual test class.

Inside the Tests folder, create a file named LoginTests.cs.

We will use the PageTest class provided by Microsoft.Playwright.NUnit.

It provides built-in browser and page lifecycle management, including test-level page initialization and cleanup.

LoginTests.cs

using Microsoft.Playwright.NUnit;

using NUnit.Framework;

using PlaywrightPOM.Pages;

using PlaywrightPOM.Utilities;

namespace PlaywrightPOM.Tests

{

    [TestFixture]

    public class LoginTests : PageTest

    {

        [Test]

        public async Task VerifySuccessfulLogin()

        {

            // Initialize page objects

            LoginPage loginPage = new LoginPage(Page);

            HomePage homePage = new HomePage(Page);

            // Open login page

            await loginPage.NavigateAsync();

            // Perform login

            await loginPage.LoginAsync(

                TestData.Username,

                TestData.Password

            );

            // Validate successful navigation

            await Expect(Page).ToHaveURLAsync(

                new System.Text.RegularExpressions.Regex(

                    “.*/inventory.html”

                )

            );

            // Validate products page title

            string title = await homePage.GetPageTitleAsync();

            Assert.That(title, Is.EqualTo(“Products”));

        }

    }

}

Explanation of the test class

PageTest: Provides Playwright’s NUnit integration and manages the browser page lifecycle.

Page: Represents the current browser tab supplied by the base class.

LoginPage: Performs login-related operations.

HomePage: Provides methods for validating the products page.

Expect(): Provides Playwright web-first assertions that automatically retry until the expected condition is satisfied or the timeout expires.

Assert.That(): Performs an NUnit assertion against the retrieved page title.

The important advantage is that the test class does not contain the actual login locators or repeated browser interaction logic.

It simply calls page object methods.

8. Running Playwright .NET Tests with NUnit

After implementing the page classes and test class, execute your automation test.

Open the project terminal and run:

dotnet test

Playwright executes the test using the default Chromium browser configuration.

If everything works correctly, you should see a successful NUnit test result.

Run the test with a visible browser:

By default, Playwright runs tests in headless mode.

To run the browser in headed mode, use the following environment variable in PowerShell:

$env:HEADED=”1″

dotnet test

You can also use Playwright’s browser configuration options through its NUnit integration.

Browser setup and cleanup

One important benefit of using PageTest is that you do not need to manually create and close the browser for every test.

The base class handles the Playwright lifecycle.

For custom frameworks, you can also manage browser instances using NUnit setup and teardown methods. However, browser contexts should be isolated between independent tests to prevent cookies, sessions, and application data from affecting other test cases.

Official documentation:

https://playwright.dev/dotnet/docs/intro

9. Real-World Workflow Using Playwright Dotnet Page Object Model

In enterprise QA automation projects, login is only the starting point.

A typical regression testing workflow may include:

Step 1: Login

Use LoginPage to authenticate the user.

Step 2: Navigate to the dashboard

Create DashboardPage with reusable navigation methods.

Step 3: Submit a form

Create FormPage with input fields, dropdowns, and submit button locators.

Step 4: Validate the result

Use Playwright assertions to verify confirmation messages and expected page navigation.

For example:

await Expect(

    Page.Locator(“.success-message”)

).ToBeVisibleAsync();

await Expect(

    Page.Locator(“.success-message”)

).ToContainTextAsync(“Submitted”);

This approach allows different tests to reuse the same page objects.

For an e-commerce application, you can extend the framework with ProductPage, CartPage, and CheckoutPage classes.

Each class should represent a meaningful application page or component.

10. Common Errors and Troubleshooting

While implementing Playwright Dotnet Page Object Model, beginners may encounter several issues.

Error 1: Browser executable not found

Reason: Required Playwright browser binaries are not installed.

Solution:

dotnet build

pwsh bin/Debug/net8.0/playwright.ps1 install

Error 2: Locator not found

Reason: The locator may be incorrect, or the application structure may have changed.

Solution: Inspect the application using browser developer tools and verify the selector.

Prefer stable locators such as IDs, accessible roles, and labels.

Error 3: Object reference not set

Reason: The IPage instance may not have been initialized correctly.

Solution: Make sure the constructor receives a valid Page instance.

LoginPage loginPage = new LoginPage(Page);

Error 4: Test timeout

Reason: The application may load slowly, or the expected element may never appear.

Solution: Verify the locator, application response, and expected state.

Avoid adding unnecessary fixed delays.

Error 5: Missing namespace or package

Reason: The required Playwright or NUnit dependency may not be installed.

Solution:

dotnet add package Microsoft.Playwright.NUnit

dotnet restore

dotnet build

Debugging techniques

Playwright provides useful debugging features, including:

  • Headed browser execution.
  • Screenshots.
  • Browser console logs.
  • Trace Viewer.
  • Locator inspection.

For example, capture a screenshot during debugging:

await Page.ScreenshotAsync(

    new PageScreenshotOptions

    {

        Path = “login-debug.png”,

        FullPage = true

    }

);

Trace Viewer is particularly useful for investigating failed test steps and browser interactions.

Documentation: https://playwright.dev/dotnet/docs/trace-viewer

11. Best Practices for Building Scalable Playwright .NET Frameworks

Follow these best practices when creating enterprise-level automation frameworks.

1. Keep locators inside page classes

Avoid declaring the same locator in multiple test classes.

2. Create reusable methods

Methods such as LoginAsync(), SearchAsync(), and SubmitFormAsync() reduce duplicate code.

3. Use meaningful class names

Use names such as LoginPage, DashboardPage, and CheckoutPage.

4. Prefer reliable locators

Use accessible roles, labels, and stable test IDs instead of fragile XPath expressions.

5. Use async and await correctly

Playwright operations should be awaited to avoid incomplete execution and synchronization problems.

6. Keep assertions primarily in test classes

Page objects should focus on application interactions. Tests should describe expected outcomes.

7. Isolate test execution

Use independent browser contexts and avoid sharing application state between unrelated tests.

8. Manage test data properly

Keep test data separate from page objects and avoid hardcoding sensitive credentials.

9. Integrate with CI/CD

Run automated tests through pipelines such as Azure DevOps or GitHub Actions.

10. Generate useful test reports

Use NUnit-compatible reporting tools and Playwright traces to investigate failures.

For more advanced architecture concepts, explore the TechSarvam pillar guide on Playwright Framework Design.

12. Playwright .NET Page Object Model Interview Questions

The following questions are useful for QA Automation Engineers, C# automation testers, and SDETs preparing for technical interviews.

Q1. What is Page Object Model in Playwright .NET?

Page Object Model is a design pattern that represents application pages using separate C# classes containing locators and reusable methods.

Q2. Why do we use IPage in Playwright .NET?

IPage represents a browser tab. It provides methods to navigate, locate elements, interact with controls, and perform browser operations.

Q3. What is the purpose of the constructor in a page class?

The constructor initializes the page object and receives the IPage instance required to interact with application elements.

Q4. What is the difference between IPage and ILocator?

IPage represents the entire browser page, whereas ILocator represents a specific element or group of elements on that page.

Q5. Can multiple test cases use the same page object class?

Yes. Multiple tests can create instances of the same page object class and reuse its methods.

Q6. How does Playwright handle synchronization?

Playwright automatically waits for relevant actionability conditions before performing actions. Its web-first assertions also retry until the expected condition is satisfied or the timeout expires.

Q7. Why should we use NUnit with Playwright .NET?

NUnit provides test execution, setup and teardown capabilities, assertions, test organization, and parallel execution support.

Q8. How do you handle multiple pages in a POM framework?

Create separate page classes and pass the appropriate IPage instance to each page object. For example, LoginPage, DashboardPage, and CheckoutPage can maintain their own locators and methods.

Leave a Comment

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