1. Introduction to Playwright C# Setup
Playwright is a browser automation framework developed by Microsoft. It allows automation engineers to interact with web applications programmatically.
Playwright supports multiple programming languages:
- C#
- JavaScript
- TypeScript
- Python
- Java
Playwright C# uses the .NET API provided through the Microsoft.Playwright NuGet package.
For example, imagine you are testing an online shopping application. You need to verify login, product search, cart functionality, and checkout.
Instead of manually performing these operations, you can create C# automation scripts that execute these scenarios automatically.
Playwright Testing Tutorial for Beginners: Install and Run Your First Test – Upbeat Geek
Running and debugging tests | Playwright
Playwright vs Selenium vs Cypress: Which to Choose in 2026? | Thinksys
5
A typical Playwright C# setup includes:
- Installing the .NET SDK.
- Creating a C# project.
- Installing Playwright NuGet packages.
- Downloading browser binaries.
- Configuring a testing framework.
- Writing and executing automated tests.
Let’s understand each step.
2. Prerequisites: .NET SDK, Visual Studio, and C# Basics
Before starting the Playwright C# setup, install the following tools.
| Requirement | Purpose |
| .NET SDK | Builds and executes C# applications |
| Visual Studio 2022 | Development environment |
| Visual Studio Code | Lightweight code editor |
| C# basics | Writing automation scripts |
| HTML and CSS basics | Understanding web elements |
| NUnit or MSTest | Test execution |
For this tutorial, we will use .NET 8 and NUnit as an example. You can also use a supported later .NET version.
Recommended environment
- Operating system: Windows 10/11, macOS, or Linux.
- .NET SDK: .NET 8 or later.
- IDE: Visual Studio 2022 or Visual Studio Code.
- Browser: Chromium, Firefox, or WebKit.
Download Visual Studio:
Download Visual Studio Code:
You should have basic knowledge of C# classes, methods, namespaces, and asynchronous programming.
3. Installing and Verifying the .NET SDK
The .NET SDK is required to create, build, and execute Playwright C# projects.
Step 1: Download .NET SDK
Visit the official Microsoft website:
Select the appropriate SDK installer for your operating system.
Setting Up Your Machine for .NET Development – Dometrain – Dometrain
For Windows:
- Download the Windows x64 SDK installer.
- Open the downloaded installer.
- Follow the installation instructions.
- Restart your terminal after installation.
For macOS, download the appropriate macOS installer or use a package manager.
For Ubuntu Linux, follow Microsoft’s official Linux installation instructions.
Step 2: Verify .NET installation
Open Command Prompt, PowerShell, or Terminal.
Execute:
dotnet –version
Example output:
8.0.xxx
The exact version depends on the installed SDK.
Step 3: Check installed SDKs
Execute:
dotnet –list-sdks
This command displays all installed .NET SDK versions.
To check installed runtimes:
dotnet –list-runtimes
If these commands work, your .NET environment is ready.
4. Creating a C# Project Using the .NET CLI
Now let’s create a new C# project for browser automation.
You can create projects through Visual Studio or the .NET command-line interface.
For beginners, the .NET CLI is a simple way to understand project creation.
Step 1: Create a project directory
Create a folder:
PlaywrightCSharpSetup
Open the folder in your terminal.
Step 2: Create an NUnit project
Execute:
dotnet new nunit -n PlaywrightTests
Navigate to the project:
cd PlaywrightTests
This command creates an NUnit-based C# test project.
Step 3: Build the project
Execute:
dotnet build
If the build succeeds, your basic NUnit project is ready.
Step 4: Open the project in Visual Studio Code
Execute:
code .
You can now view and edit your C# files.
5. Installing Microsoft.Playwright and Required Packages
After creating the NUnit project, install the Playwright package.
Playwright provides official NuGet packages for .NET applications.
Step 1: Install Microsoft.Playwright.NUnit
Execute:
dotnet add package Microsoft.Playwright.NUnit
This package provides Playwright’s NUnit integration, including browser management and test fixtures.
If you want to use Playwright without NUnit, install the core package:
dotnet add package Microsoft.Playwright
Step 2: Verify installed packages
Run:
dotnet list package
You should see the installed Playwright and NUnit dependencies.
Step 3: Build the project
dotnet build
Building the project generates the Playwright browser installation script in the output directory.
Your project file will contain package references similar to these:
<Project Sdk=”Microsoft.NET.Sdk”>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include=”Microsoft.Playwright.NUnit”
Version=”YOUR_INSTALLED_VERSION” />
</ItemGroup>
</Project>
The package version is managed by NuGet. Keep it consistent across your development and CI/CD environments.
6. Installing Chromium, Firefox, and WebKit Browsers
Installing the Playwright NuGet package does not automatically download all browser binaries.
You must install the browsers separately.
Step 1: Install all supported browsers
On Windows PowerShell:
pwsh bin/Debug/net8.0/playwright.ps1 install
On macOS or Linux:
pwsh bin/Debug/net8.0/playwright.sh install
If you use a different target framework or build configuration, update the output path accordingly.
Step 2: Install individual browsers
To install Chromium:
pwsh bin/Debug/net8.0/playwright.ps1 install chromium
To install Firefox:
pwsh bin/Debug/net8.0/playwright.ps1 install firefox
To install WebKit:
pwsh bin/Debug/net8.0/playwright.ps1 install webkit
Step 3: Install Linux dependencies
For Linux environments, browser system dependencies may also be required.
Execute:
pwsh bin/Debug/net8.0/playwright.sh install –with-deps
Playwright Testing Tutorial for Beginners: Install and Run Your First Test – Upbeat Geek
Important: Playwright downloads browser versions compatible with its installed package. If you update the NuGet package, run the browser installation command again.
7. Writing and Running the First Playwright C# Test
Now that your environment is ready, let’s create your first browser automation test.
Step 1: Create a test file
Inside the project, create:
Tests/FirstPlaywrightTest.cs
Step 2: Add the following C# code
using Microsoft.Playwright;
using Microsoft.Playwright.NUnit;
using NUnit.Framework;
namespace PlaywrightTests.Tests;
public class FirstPlaywrightTest : PageTest
{
[Test]
public async Task VerifyHomepage()
{
await Page.GotoAsync(“https://example.com”);
await Expect(Page)
.ToHaveTitleAsync(“Example Domain”);
await Expect(Page.Locator(“h1”))
.ToBeVisibleAsync();
}
}
Understanding the code
- PageTest provides a browser page and manages its lifecycle.
- [Test] identifies the NUnit test method.
- Page.GotoAsync() navigates to the website.
- Expect() performs an assertion.
- ToBeVisibleAsync() verifies that an element is visible.
Step 3: Execute the test
Run:
dotnet test
The test runner launches the browser in headless mode and executes the test.
Expected result:
Test Run Successful.
Total tests: 1
Passed: 1
Failed: 0
The exact output depends on your test runner version.
Understanding async and await
One important concept in Playwright C# setup is asynchronous programming.
Playwright APIs such as GotoAsync(), ClickAsync(), and FillAsync() return tasks.
Consider:
public async Task OpenApplication()
{
await Page.GotoAsync(“https://example.com”);
await Page.Locator(“h1”).IsVisibleAsync();
}
async marks a method that can perform asynchronous operations.- await waits for an asynchronous operation to complete.
- Task represents an asynchronous operation.
Using await ensures browser actions execute in the correct sequence without blocking the calling thread.
8. Configuring NUnit or MSTest and Test Execution
Playwright .NET supports NUnit, MSTest, and xUnit.
For this setup tutorial, we are using NUnit because its integration provides ready-made browser fixtures.
NUnit configuration
Install the NUnit integration:
dotnet add package Microsoft.Playwright.NUnit
using Microsoft.Playwright.NUnit;
using NUnit.Framework;
namespace PlaywrightTests.Tests;
[TestFixture]
public class LoginTests : PageTest
{
[Test]
public async Task VerifyLoginPage()
{
await Page.GotoAsync(“https://example.com”);
await Expect(Page)
.ToHaveTitleAsync(“Example Domain”);
}
}
The PageTest class provides a new page and browser context for each test and handles their cleanup.
MSTest configuration
If your project uses MSTest, install:
dotnet add package Microsoft.Playwright.MSTest
A basic MSTest example is:
using Microsoft.Playwright.MSTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class HomepageTests : PageTest
{
[TestMethod]
public async Task VerifyHomepage()
{
await Page.GotoAsync(“https://example.com”);
await Expect(Page)
.ToHaveTitleAsync(“Example Domain”);
}
}
Use the appropriate test framework’s namespace, attributes, and base class. Do not mix NUnit and MSTest packages in the same test class.
Running tests from the command line
Execute all tests:
dotnet test
Build without running tests:
dotnet build
Run a specific test:
dotnet test –filter “FullyQualifiedName~VerifyHomepage”
Generate a test result file:
dotnet test –logger “trx;LogFileName=results.trx”
The TRX file contains structured test execution information that can be published in CI/CD pipelines.
9. Project Structure and Page Object Model Setup
A well-organized project makes automation code easier to maintain.
For larger QA engineering projects, avoid keeping every test case in a single file.
Use the Page Object Model (POM) design pattern.
Recommended project structure
PlaywrightTests/
│
├── Pages/
│ ├── LoginPage.cs
│ └── HomePage.cs
│
├── Tests/
│ ├── LoginTests.cs
│ └── HomeTests.cs
│
├── Utilities/
│ └── TestConfig.cs
│
├── TestData/
│
├── TestResults/
│
└── PlaywrightTests.csproj
Step 1: Create LoginPage.cs
using Microsoft.Playwright;
namespace PlaywrightTests.Pages;
public class LoginPage
{
private readonly IPage _page;
public LoginPage(IPage page)
{
_page = page;
}
private ILocator Username =>
_page.GetByLabel(“Username”);
private ILocator Password =>
_page.GetByLabel(“Password”);
private ILocator LoginButton =>
_page.GetByRole(
AriaRole.Button,
new() { Name = “Login” }
);
public async Task NavigateAsync()
{
await _page.GotoAsync(
“https://example.com/login”
);
}
public async Task LoginAsync(
string username,
string password)
{
await Username.FillAsync(username);
await Password.FillAsync(password);
await LoginButton.ClickAsync();
}
}
Step 2: Create LoginTests.cs
using Microsoft.Playwright.NUnit;
using NUnit.Framework;
using PlaywrightTests.Pages;
namespace PlaywrightTests.Tests;
public class LoginTests : PageTest
{
[Test]
public async Task ValidLoginTest()
{
var loginPage = new LoginPage(Page);
await loginPage.NavigateAsync();
await loginPage.LoginAsync(
“testuser”,
“password123”
);
await Expect(Page.GetByText(“Welcome”))
.ToBeVisibleAsync();
}
}
The example selectors and expected message should be adjusted to match your actual application.
Benefits of POM:
- Reduces duplicate code.
- Improves code readability.
- Makes maintenance easier.
- Separates test logic from page interactions.
- Supports reusable automation components.
For enterprise-level projects, you can extend POM with configuration management, test data management, logging, and reporting.
10. Debugging, Screenshots, Reporting, and Common Errors
After completing the Playwright C# setup, learn how to debug failed tests and generate execution reports.
A. Capturing screenshots
Screenshots help QA engineers understand the application state when a test fails.
Example:
await Page.ScreenshotAsync(
new PageScreenshotOptions
{
Path = “screenshots/homepage.png”,
FullPage = true
}
);
Make sure the screenshots directory exists before executing the test.
B. Debugging with Playwright Inspector
Playwright provides an Inspector that allows you to pause execution, inspect elements, and debug locators.
In Windows PowerShell:
$env:PWDEBUG=”1″
dotnet test
You can also use Visual Studio debugging breakpoints to investigate C# test failures.
C. Generating test reports
NUnit test execution results can be generated in TRX format.
Run:
dotnet test –logger “trx;LogFileName=results.trx”
For HTML reporting, you can use compatible reporting tools such as Allure or NUnit report generators.
Remember the difference:
- TRX files contain structured test results.
- HTML reports provide a browser-readable presentation.
- CI/CD artifacts preserve reports for later access.
D. Common Playwright C# setup errors
| Error | Possible solution |
| dotnet command not found | Install and configure .NET SDK |
| Browser executable missing | Run Playwright browser installation |
| Package not found | Check NuGet package name and restore dependencies |
| Test not discovered | Verify test framework packages and attributes |
| Timeout exception | Check locator and application response |
| Screenshot not saved | Verify directory and permissions |
| Browser launch failure | Install required system dependencies |
E. Troubleshooting commands
Restore NuGet dependencies:
dotnet restore
Clean the project:
dotnet clean
Rebuild:
dotnet build
Install browsers again:
pwsh bin/Debug/net8.0/playwright.ps1 install
These commands help resolve common dependency, build, and browser installation problems.
11. GitHub Actions and Azure DevOps CI/CD Integration
In real-world QA engineering projects, automation tests are executed through CI/CD pipelines.
You can configure Playwright C# tests to run whenever developers push code changes.
A. GitHub Actions integration
Create the following file:
.github/workflows/playwright.yml
Add this YAML configuration:
name: Playwright CSharp Tests
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
– name: Checkout Code
uses: actions/checkout@v4
– name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
– name: Restore Packages
run: dotnet restore
– name: Build Project
run: dotnet build
– name: Install Browsers
run: |
pwsh bin/Debug/net8.0/playwright.sh install –with-deps
– name: Execute Tests
run: |
dotnet test –logger “trx;LogFileName=results.trx”
– name: Upload Test Results
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-test-results
path: “**/TestResults/**/*.trx”
if-no-files-found: warn
This workflow performs the following operations:
- Downloads the repository.
- Installs the .NET SDK.
- Restores NuGet dependencies.
- Builds the project.
- Installs Playwright browsers.
- Executes automated test scripts.
- Uploads test results as artifacts.
The reports can be downloaded from the workflow run’s Artifacts section.
B. Azure DevOps integration
Create a file named:
azure-pipelines.yml
Add:
trigger:
– main
pool:
vmImage: ubuntu-latest
steps:
– task: UseDotNet@2
inputs:
packageType: sdk
version: ‘8.x’
– script: dotnet restore
displayName: Restore Packages
– script: dotnet build
displayName: Build Project
– script: |
pwsh bin/Debug/net8.0/playwright.sh install –with-deps
displayName: Install Browsers
– script: dotnet test –logger trx
displayName: Execute Tests
– task: PublishTestResults@2
condition: always()
inputs:
testResultsFormat: VSTest
testResultsFiles: ‘**/*.trx’
failTaskOnFailedTests: true
This pipeline installs .NET, builds the project, installs browser dependencies, executes tests, and publishes test results.
Important: These examples assume a Debug build targeting .NET 8. If you use a different target framework or build configuration, adjust the generated Playwright script path.
12. Best Practices for Playwright C# Setup
Follow these recommendations when building a professional automation framework:
- Use a supported .NET SDK version.
- Keep Playwright packages updated.
- Install matching browser binaries after package updates.
- Use NUnit or MSTest consistently.
- Prefer user-facing locators such as GetByRole() and GetByLabel().
- Use async and await for browser operations.
- Avoid unnecessary fixed waits.
- Implement Page Object Model for reusable code.
- Capture screenshots and traces for failed tests.
- Execute regression tests across multiple browsers.
- Store credentials securely.
- Integrate automated tests with CI/CD pipelines.
For Indian QA Automation Engineers and SDETs preparing for interviews, practical knowledge of .NET CLI commands, NuGet packages, NUnit, POM, and CI/CD integration is particularly useful.
Be prepared to explain how you installed Playwright, configured browsers, executed test cases, and resolved common environment issues.
13. Frequently Asked Questions (FAQs)
1. What is Playwright C# setup?
Playwright C# setup is the process of configuring the .NET development environment, installing Microsoft.Playwright packages, downloading browser binaries, and preparing a C# project for browser automation.
2. How do I get started with Playwright C# setup?
Install the .NET SDK, create an NUnit project, install the Playwright NUnit package, build the project, and install browsers.
Start with:
dotnet new nunit -n PlaywrightTests
cd PlaywrightTests
dotnet add package Microsoft.Playwright.NUnit
dotnet build
Then install browsers and execute your first test using dotnet test.
3. What are the benefits of Playwright C# setup?
It allows you to build browser automation frameworks using C#, perform cross-browser testing, automate regression scenarios, capture screenshots, debug failures, and integrate tests with CI/CD pipelines.
4. Which browsers are supported by Playwright C#?
Playwright supports Chromium, Firefox, and WebKit. You can install these browsers and execute the same automation scenarios across different browser engines.
5. Can beginners learn Playwright C#?
Yes. Beginners with basic C# knowledge can start with project setup, navigation, locators, and assertions before learning NUnit, POM, reporting, and CI/CD.
6. Is Visual Studio mandatory for Playwright C#?
No. You can use Visual Studio, Visual Studio Code, or another compatible editor. The .NET CLI can handle project creation, package installation, building, and test execution.
7. Can Playwright C# be used for regression testing?
Yes. You can create reusable automated test suites and execute them whenever application code changes. This helps identify defects introduced by new releases.
