Browse all tutorials →
Tutorial November 20, 2026 12 min read

Playwright C# .NET Tutorial: NUnit, MSTest & Your First Test

Playwright for .NET gives C# teams the same fast, auto-waiting browser automation as the Node version, inside the test framework you already use. This guide takes you from dotnet new to a parallel, traced test suite.

🧪

Quick answer: install Microsoft.Playwright.NUnit, inherit from PageTest

Create an NUnit project, add the Microsoft.Playwright.NUnit package, build once, run playwright.ps1 install to download browsers, then write tests that inherit from PageTest. dotnet test runs them.

Why Playwright for .NET teams

Playwright for .NET is Microsoft's official C# binding for Playwright. If your application and your developers live in C#, writing the UI tests in C# keeps everything in one solution, one CI pipeline and one language your whole team can review. You get the same core features as the Node version:

  • Auto-waiting. Actions wait for elements to be visible, enabled and stable before clicking or typing.
  • Web-first assertions. Expect(...).ToBeVisibleAsync() retries until the condition is true or the timeout hits.
  • Every engine. Chromium, Firefox and WebKit from one API, plus branded Chrome and Edge.
  • Isolation. Each test gets a fresh browser context, so cookies and storage never leak between tests.

If you're coming from Selenium WebDriver in C#, the biggest change is that you stop writing explicit waits. Our Selenium to Playwright migration guide covers the mindset shift.

Install Playwright for .NET

You need the .NET 8 SDK (or newer) and PowerShell 7 (pwsh), which runs the browser install script on Windows, macOS and Linux.

Terminal
# 1. Create an NUnit test project
dotnet new nunit -n PlaywrightTests
cd PlaywrightTests

# 2. Add the Playwright NUnit package
dotnet add package Microsoft.Playwright.NUnit

# 3. Build once so the install script is generated
dotnet build

# 4. Download the browsers (use your target framework folder)
pwsh bin/Debug/net8.0/playwright.ps1 install

Tip: on a fresh Linux CI agent, add --with-deps to the install command so it also installs the system libraries the browsers need.

Your first Playwright NUnit test

Replace the generated UnitTest1.cs with this. The PageTest base class gives every test a fresh Page, plus Context, Browser and the Expect assertion helper.

HomePageTests.cs
using System.Text.RegularExpressions;
using Microsoft.Playwright;
using Microsoft.Playwright.NUnit;
using NUnit.Framework;

namespace PlaywrightTests;

[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class HomePageTests : PageTest
{
    [Test]
    public async Task HasTitle()
    {
        await Page.GotoAsync("https://playwright.dev");
        await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
    }

    [Test]
    public async Task GetStartedLinkOpensInstallation()
    {
        await Page.GotoAsync("https://playwright.dev");
        await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync();
        await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" }))
            .ToBeVisibleAsync();
    }
}

Run it with dotnet test. Tests run headless in Chromium by default. Every Playwright call is async, so test methods return Task and every action is awaited. A missing await is the most common bug in new .NET suites: the test finishes before the click happens.

MSTest and xUnit versions

The pattern is identical; only the package and attributes change.

FrameworkPackageAttributes
NUnitMicrosoft.Playwright.NUnit[TestFixture], [Test]
MSTestMicrosoft.Playwright.MSTest[TestClass], [TestMethod]
xUnitMicrosoft.Playwright.Xunit[Fact]
MSTest
using Microsoft.Playwright.MSTest;

[TestClass]
public class HomePageTests : PageTest
{
    [TestMethod]
    public async Task HasTitle()
    {
        await Page.GotoAsync("https://playwright.dev");
        await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
    }
}

Locators and assertions in C#

The locator strategy is the same as every other Playwright language: prefer what the user sees. Options are passed as object initialisers.

Locators
// Best: role + accessible name
Page.GetByRole(AriaRole.Button, new() { Name = "Sign in" });

// Form fields by their label
Page.GetByLabel("Email");

// Stable test ids (data-testid by default)
Page.GetByTestId("checkout-total");

// Filter a list down to one row
Page.GetByRole(AriaRole.Listitem).Filter(new() { HasText = "Order #1042" });
Web-first assertions
await Expect(Page.GetByText("Welcome back")).ToBeVisibleAsync();
await Expect(Page.GetByLabel("Email")).ToHaveValueAsync("qa@example.com");
await Expect(Page.GetByRole(AriaRole.Listitem)).ToHaveCountAsync(3);
await Expect(Page).ToHaveURLAsync(new Regex(".*/dashboard"));

Avoid Assert.That(await locator.IsVisibleAsync()). It checks once and fails if the element is a few milliseconds late; Expect retries. The locators guide and assertions guide go deeper; the examples are TypeScript, but the method names map one to one (getByRole becomes GetByRole).

New to test automation?

Learn Playwright fundamentals step by step, then add Claude Code and the MCP Server.

See the course plan →

Running tests: browsers, headed mode, filters

Terminal
# All tests, headless Chromium
dotnet test

# Another engine
dotnet test -- Playwright.BrowserName=webkit

# Watch the browser
dotnet test -- Playwright.LaunchOptions.Headless=false

# One test or a group by name
dotnet test --filter "Name~GetStarted"

# Step through with the Playwright Inspector (bash; in PowerShell use $env:PWDEBUG=1)
PWDEBUG=1 dotnet test

Configuration with .runsettings and ContextOptions

Put shared settings in a .runsettings file and pass it with dotnet test --settings test.runsettings:

test.runsettings
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <NUnit>
    <NumberOfTestWorkers>4</NumberOfTestWorkers>
  </NUnit>
  <Playwright>
    <BrowserName>chromium</BrowserName>
    <ExpectTimeout>5000</ExpectTimeout>
    <LaunchOptions>
      <Headless>true</Headless>
      <Channel>msedge</Channel>
    </LaunchOptions>
  </Playwright>
</RunSettings>

Per-context options such as viewport, locale or base URL go in an override on your test class:

ContextOptions override
public override BrowserNewContextOptions ContextOptions() => new()
{
    BaseURL = "https://staging.example.com",
    ViewportSize = new() { Width = 1280, Height = 720 },
    Locale = "en-US",
};

With BaseURL set, Page.GotoAsync("/login") resolves against it, so the same suite runs against any environment.

Codegen and the Trace Viewer

Codegen records your clicks and writes C# for you. It is the fastest way to find a good locator:

Terminal
pwsh bin/Debug/net8.0/playwright.ps1 codegen https://playwright.dev

Pick Library or NUnit/MSTest in the target dropdown. Treat the output as a draft: keep the locators, then add real assertions.

The Trace Viewer shows every action with a DOM snapshot, network calls and console logs. Record a trace per test:

Tracing
[SetUp]
public async Task StartTrace() =>
    await Context.Tracing.StartAsync(new()
    {
        Title = TestContext.CurrentContext.Test.Name,
        Screenshots = true, Snapshots = true, Sources = true,
    });

[TearDown]
public async Task StopTrace() =>
    await Context.Tracing.StopAsync(new()
    {
        Path = Path.Combine(TestContext.CurrentContext.WorkDirectory,
            "playwright-traces", $"{TestContext.CurrentContext.Test.Name}.zip"),
    });

Open one with pwsh bin/Debug/net8.0/playwright.ps1 show-trace path/to/trace.zip, or drop the zip on trace.playwright.dev. In CI, save traces only for failed tests to keep artifacts small.

Page Object Model in C#

Once a flow appears in more than two tests, move it into a page object. C# 12 primary constructors keep it short:

Pages/LoginPage.cs
public class LoginPage(IPage page)
{
    private ILocator Email => page.GetByLabel("Email");
    private ILocator Password => page.GetByLabel("Password");
    private ILocator SignIn => page.GetByRole(AriaRole.Button, new() { Name = "Sign in" });

    public Task GotoAsync() => page.GotoAsync("/login");

    public async Task LoginAsync(string email, string password)
    {
        await Email.FillAsync(email);
        await Password.FillAsync(password);
        await SignIn.ClickAsync();
    }
}

// In a test
var login = new LoginPage(Page);
await login.GotoAsync();
await login.LoginAsync("qa@example.com", Environment.GetEnvironmentVariable("QA_PASSWORD")!);
await Expect(Page).ToHaveURLAsync(new Regex(".*/dashboard"));

Keep assertions in the tests, not in the page objects, so each test still says what it checks. The Page Object Model tutorial covers folder structure and naming.

Playwright C# vs TypeScript

FeatureC# / .NETTypeScript / Node
Browser automation APIFullFull
Test runnerNUnit, MSTest, xUnitPlaywright Test (built in)
Codegen, Inspector, Trace ViewerYesYes
UI mode, HTML reporterNoYes
Playwright Test AgentsNoYes
ParallelismVia the test frameworkBuilt in, with sharding
Community examplesFewerMost tutorials and courses

Choose C# when your product team works in .NET and will maintain the tests. Choose TypeScript when QA owns the suite on its own and you want the newest features first, especially the AI tooling: Playwright Test Agents and the MCP-based workflows are Node-first.

How to learn Playwright for C#

Learn the concepts first (locators, auto-waiting, web-first assertions, isolation, page objects), then the C# syntax. Most Playwright learning material is in JavaScript or TypeScript, and that is fine: once you know page.getByRole(...), writing Page.GetByRole(...) takes minutes.

Playwright + Claude AI & MCP Server: AI QA Automation 2026 teaches Playwright in JavaScript, not C#. It is still a useful next step: the locators, assertions, auto-waiting and Page Object Model you learn there are the same Playwright API with different casing, so everything carries over to C#. It then adds Claude Code, the Playwright MCP Server and Playwright Test Agents. See the course plan for what each section covers.


Frequently Asked Questions

Does Playwright support C#?

Yes. Microsoft maintains an official .NET package, Microsoft.Playwright, with the same browser support as the Node version: Chromium, Firefox and WebKit, plus branded Chrome and Edge.

Which test framework should I use with Playwright .NET?

NUnit is the most common choice and the one the official docs use first. MSTest and xUnit have their own base-class packages (Microsoft.Playwright.MSTest and Microsoft.Playwright.Xunit). Pick the one your team already uses.

How do I install Playwright browsers in .NET?

Build the project once, then run pwsh bin/Debug/net8.0/playwright.ps1 install. Swap net8.0 for your target framework folder. PowerShell 7 must be installed to run the script.

Is Playwright C# slower than TypeScript?

Not in any way that matters for tests. Both drive the same browser engines; most test time is spent waiting on the app, not in the client language.

Can I use Playwright Test Agents or UI mode with C#?

No. UI mode, the HTML reporter and Playwright Test Agents belong to the Node test runner (@playwright/test). In .NET you get the automation library, codegen, the Inspector and the Trace Viewer.

Can I run Playwright C# tests in parallel?

Yes. Mark fixtures with [Parallelizable(ParallelScope.Self)] and set NumberOfTestWorkers in a .runsettings file. Each test gets its own isolated browser context.

Asim Noaman, Playwright and Claude AI course instructor

Asim Noaman

Sr. SQA Manager & AI Automation Engineer

18+ years in QA. Asim currently runs an 80+ engineer QA function at Tkxel and built a Testing Center of Excellence for a major Saudi bank. He builds AI testing agents with Playwright, Claude AI and the MCP Server at work, and teaches the same workflow in his courses.

18+ Years in QA 80+ engineer QA function
Udemy Instructor 4.5★ · 140+ ratings · 570+ students
Anthropic Certificates Claude API · MCP
Connect on LinkedIn

Full profile →

Playwright + Claude AI Course on Udemy

Learn Playwright Once. Use It in Any Language.

The course teaches Playwright in JavaScript from zero: locators, assertions, hooks and the Page Object Model, which map directly to the .NET API. Then it adds Claude Code, the Playwright MCP Server and Playwright Test Agents. 107 lectures, 11.5 hours, rated 4.5★ from 140+ ratings, 570+ students.

  • Playwright from scratch in JavaScript, no prior coding needed
  • Page Object Model, hooks and timeouts
  • Claude Code, custom QA subagents and the Playwright MCP Server
  • Multi-agent workflows and Playwright Test Agents
Enroll on Udemy →