Back to "Multi-browser E2E Testing con Playwright per .NET"

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

E2E Testing Multi-Browser Playwright Testing xUnit

Multi-browser E2E Testing con Playwright per .NET

Thursday, 27 November 2025

Playwright è la soluzione ufficiale di Microsoft per l'automazione del browser moderno, offrendo supporto multi-browser (Chrome, Firefox, Safari) con una singola API, built-in traccia di debug, e l'emulazione mobile. Questa guida copre tutto, dalla configurazione ai modelli di test avanzati, confrontandolo con PuppeteerSharp per aiutarti a scegliere lo strumento giusto. Se hai solo bisogno di Chrome e vuoi una configurazione più semplice, considerare PuppeteerSharp invece - ma se avete bisogno di test cross-browser completo, Playwright è la strada da seguire.

Introduzione

Se hai letto il mio articolo su PuppeteerSharp, saprete che sono un fan dei moderni strumenti di test E2E che non ti fanno desiderare di strappare i capelli fuori . PuppeteerSharp è brillante per Chrome-solo testing , ma cosa succede se avete bisogno di testare su più browser ? Ecco dove PlaywrightCity name (optional, probably does not need a translation) Entra.

Playwright è la risposta di Microsoft al problema di automazione del browser, e hanno imparato da tutto ciò che è venuto prima. E 'come il fratello più ambizioso di PuppeteerSharp - fa tutto ciò che Puppeteer fa, ma aggiunge Firefox e il supporto Safari, meglio in attesa di auto, e una serie di strumenti di debug che rendono la ricerca di problemi un doddle assoluto.

In questo articolo , Vi mostrerò come utilizzare Playwright per .NET per testare Chrome , Firefox , e Safari , con esempi di codice reale e modelli pratici è possibile utilizzare oggi .

Perché Playwright Over PuppeteerSharp?

Non fraintendermi PuppeteerSharp è eccellente se hai solo bisogno di Chrome. Ma qui è quando Playwright ha senso:

Il problema del multi-browser

I tuoi utenti non tutti utilizzano Chrome. Essi utilizzano:

  • Cromo/Orlo: ~65% degli utenti (a base di cromo)
  • SafariCity name (optional, probably does not need a translation): ~20% degli utenti (soprattutto mobili)
  • Firefox: ~5% degli utenti (ma spesso rendering diversi)

Un bug che appare solo in Safari può perdere il 20% dei tuoi potenziali utenti. Playwright consente di testare tutti e tre con la stessa API.

Migliore esperienza degli sviluppatori

graph TB
    subgraph "PuppeteerSharp"
        PS[Chrome Only]
        PS --> PS1[Fast setup]
        PS --> PS2[Simple API]
        PS --> PS3[Chrome DevTools]
    end

    subgraph "Playwright"
        PW[Multi-Browser]
        PW --> PW1[Chrome, Firefox, Safari]
        PW --> PW2[Auto-waiting built-in]
        PW --> PW3[Trace viewer]
        PW --> PW4[Codegen tool]
        PW --> PW5[Better error messages]
    end

    style PW stroke:#00aa00,stroke-width:3px
    style PW1 stroke:#0066cc,stroke-width:2px
    style PW3 stroke:#0066cc,stroke-width:2px
    style PW4 stroke:#0066cc,stroke-width:2px

Vantaggi chiave

  1. Supporto multi-browser - Test Chrome, Firefox, Safari con codice identico
  2. Meglio attesa automatica - Più affidabile fuori dalla scatola, meno test sgradevoli
  3. Visualizzatore traccia - Registrare tracce complete delle prove per il debug
  4. CodegenCity name (optional, probably does not need a translation) - Generare il codice di prova interagendo con il tuo sito
  5. Intercettazione della rete - Più potente di PuppeteerSharp
  6. Caratteristiche web moderne - Migliore supporto per l'Ombra DOM, iframe, ecc.

Impostazione di Playwright per .NET

Installare il Microsoft.Playwright Pacchetto NuGet:

dotnet add package Microsoft.Playwright
dotnet add package Microsoft.Playwright.NUnit  # Or use xUnit

Quindi installare i browser (questi download Cromo, Firefox, e WebKit):

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

O su Linux/Mac:

playwright install

Nota: Il primo browser installa download circa 400MB. Gli aggiornamenti successivi sono molto più piccoli.

Ecco la mia configurazione del progetto di test:

<PackageReference Include="Microsoft.Playwright" Version="1.48.0" />
<PackageReference Include="Microsoft.Playwright.NUnit" Version="1.48.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

Sto usando xUnit, ma Playwright funziona ugualmente bene con NUnitCity name (optional, probably does not need a translation) oppure MSTestCity name (optional, probably does not need a translation). Infatti, Playwright ha un dedicato Integrazione NUnit con altri aiutanti.

Creazione di una classe di prova di base

Simile a PuppeteerSharp, ma con supporto multi-browser:

Struttura della classe

using Microsoft.Playwright;
using Xunit.Abstractions;

namespace Mostlylucid.Test.E2E;

public abstract class PlaywrightTestBase : IAsyncLifetime
{
    protected IPlaywright Playwright = null!;
    protected IBrowser Browser = null!;
    protected IBrowserContext Context = null!;
    protected IPage Page = null!;

    protected readonly ITestOutputHelper Output;
    protected const string BaseUrl = "http://localhost:8080";

    // Override this in derived classes to test different browsers
    protected virtual BrowserType BrowserType => BrowserType.Chromium;

    protected PlaywrightTestBase(ITestOutputHelper output)
    {
        Output = output;
    }

    public async Task InitializeAsync()
    {
        // Create Playwright instance
        Playwright = await Microsoft.Playwright.Playwright.CreateAsync();

        // Launch the specified browser
        Browser = await LaunchBrowserAsync();

        // Create a new context (like an incognito window)
        Context = await Browser.NewContextAsync(new BrowserNewContextOptions
        {
            ViewportSize = new ViewportSize { Width = 1400, Height = 900 },
            IgnoreHTTPSErrors = true
        });

        // Create a new page
        Page = await Context.NewPageAsync();

        // Set default timeout
        Page.SetDefaultTimeout(30000);
    }

    private async Task<IBrowser> LaunchBrowserAsync()
    {
        var options = new BrowserTypeLaunchOptions
        {
            Headless = true, // Set to false for debugging
        };

        return BrowserType switch
        {
            BrowserType.Chromium => await Playwright.Chromium.LaunchAsync(options),
            BrowserType.Firefox => await Playwright.Firefox.LaunchAsync(options),
            BrowserType.Webkit => await Playwright.Webkit.LaunchAsync(options),
            _ => throw new ArgumentException($"Unknown browser type: {BrowserType}")
        };
    }

    public async Task DisposeAsync()
    {
        await Page?.CloseAsync()!;
        await Context?.CloseAsync()!;
        await Browser?.CloseAsync()!;
        Playwright?.Dispose();
    }
}

public enum BrowserType
{
    Chromium,
    Firefox,
    Webkit
}

Perché i contesti del browser?

Notare che creiamo un Context prima di creare un Page. Questo è un concetto Playwright che PuppeteerSharp non ha:

  • Contesto = Sessione del browser isolata (come in modalità in incognito)
  • Pagina = Una scheda all'interno di tale contesto

I contesti ti permettono di:

  • Prova con diverse sessioni utente contemporaneamente
  • Imposta diversi cookie, autorizzazioni o locali per contesto
  • Isolare completamente i test (anche all'interno della stessa istanza del browser)

Metodi helper

// Navigation with better waiting
protected async Task NavigateAsync(string path)
{
    var url = path.StartsWith("http") ? path : $"{BaseUrl}{path}";
    await Page.GotoAsync(url, new PageGotoOptions
    {
        WaitUntil = WaitUntilState.NetworkIdle
    });
}

// Playwright has better built-in waiting, but these are still useful
protected async Task<IElementHandle?> WaitForSelectorAsync(string selector)
{
    try
    {
        return await Page.WaitForSelectorAsync(selector, new PageWaitForSelectorOptions
        {
            State = WaitForSelectorState.Visible
        });
    }
    catch (TimeoutException)
    {
        return null;
    }
}

// Improved element operations with auto-waiting
protected async Task<bool> ElementExistsAsync(string selector)
{
    return await Page.Locator(selector).CountAsync() > 0;
}

protected async Task<string?> GetTextContentAsync(string selector)
{
    var locator = Page.Locator(selector);
    return await locator.TextContentAsync();
}

protected async Task TypeAsync(string selector, string text)
{
    await Page.Locator(selector).FillAsync(text);
}

protected async Task ClickAsync(string selector)
{
    await Page.Locator(selector).ClickAsync();
}

Locator - Arma segreta di Playwright

Notare la Page.Locator() Questo è diverso da PuppeteerSharp QuerySelector. I localizzatori sono:

  • Pigro - Non interrogano il DOM finche' non li usi.
  • Riprova - Aspettano e riprovano automaticamente le operazioni
  • Rigoroso - Si sbagliano se gli elementi multipli corrispondono (prevenire test flaky)
// PuppeteerSharp way (manual waiting)
await Page.WaitForSelectorAsync("#button");
await Page.ClickAsync("#button");

// Playwright way (auto-waiting)
await Page.Locator("#button").ClickAsync(); // Waits automatically!

Test multi-browser

Qui è dove Playwright brilla. È possibile eseguire lo stesso test su tutti i browser:

Utilizzo della teoria xUnit per test multi-browser

public class CrossBrowserTests : PlaywrightTestBase
{
    public CrossBrowserTests(ITestOutputHelper output) : base(output) { }

    [Theory]
    [InlineData(BrowserType.Chromium)]
    [InlineData(BrowserType.Firefox)]
    [InlineData(BrowserType.Webkit)]
    public async Task HomePage_LoadsCorrectly_InAllBrowsers(BrowserType browserType)
    {
        // Override the browser type for this test
        BrowserType = browserType;
        await InitializeAsync();

        // Arrange & Act
        await NavigateAsync("/");

        // Assert
        var title = await Page.TitleAsync();
        Assert.Contains("Mostlylucid", title);

        Output.WriteLine($"✓ Test passed in {browserType}");
    }
}

Classi di prova specifiche del browser

Oppure creare classi di test separate per ciascun browser:

public class ChromiumTests : PlaywrightTestBase
{
    protected override BrowserType BrowserType => BrowserType.Chromium;

    public ChromiumTests(ITestOutputHelper output) : base(output) { }

    [Fact]
    public async Task FilterBar_WorksInChrome()
    {
        await NavigateAsync("/blog");

        await Page.Locator("#LanguageDropDown button").ClickAsync();
        await Page.Locator("#LanguageDropDown li:has-text('Spanish')").ClickAsync();

        var url = Page.Url;
        Assert.Contains("language=es", url);
    }
}

public class FirefoxTests : PlaywrightTestBase
{
    protected override BrowserType BrowserType => BrowserType.Firefox;

    public FirefoxTests(ITestOutputHelper output) : base(output) { }

    [Fact]
    public async Task FilterBar_WorksInFirefox()
    {
        // Same test, different browser!
        await NavigateAsync("/blog");

        await Page.Locator("#LanguageDropDown button").ClickAsync();
        await Page.Locator("#LanguageDropDown li:has-text('Spanish')").ClickAsync();

        var url = Page.Url;
        Assert.Contains("language=es", url);
    }
}

public class SafariTests : PlaywrightTestBase
{
    protected override BrowserType BrowserType => BrowserType.Webkit;

    public SafariTests(ITestOutputHelper output) : base(output) { }

    [Fact]
    public async Task FilterBar_WorksInSafari()
    {
        await NavigateAsync("/blog");

        await Page.Locator("#LanguageDropDown button").ClickAsync();
        await Page.Locator("#LanguageDropDown li:has-text('Spanish')").ClickAsync();

        var url = Page.Url;
        Assert.Contains("language=es", url);
    }
}

Test di scrittura - Il modo Playwright

Vediamo esempi reali che mostrano i vantaggi di Playwright:

Test HTMX con Auto-Waiting

[Fact]
public async Task SortingDropdown_UpdatesContentViaHTMX()
{
    // Arrange
    await NavigateAsync("/blog");

    // Get first post title before sorting
    var firstPostBefore = await Page.Locator("article h2 a").First.TextContentAsync();
    Output.WriteLine($"First post before: {firstPostBefore}");

    // Act - Change sort order
    await Page.Locator("#orderSelect").SelectOptionAsync("date_asc");

    // Playwright automatically waits for HTMX to update the DOM!
    await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);

    // Assert - Content should have changed
    var firstPostAfter = await Page.Locator("article h2 a").First.TextContentAsync();
    Output.WriteLine($"First post after: {firstPostAfter}");

    var selectValue = await Page.Locator("#orderSelect").InputValueAsync();
    Assert.Equal("date_asc", selectValue);
}

Test delle interazioni Alpine.js

Maniglie Playwright Alpine.js reattività e animazioni senza soluzione di continuità:

[Fact]
public async Task AlpineDropdown_OpensAndCloses()
{
    await NavigateAsync("/blog");

    // Click to open dropdown (Alpine.js controlled)
    await Page.Locator("#LanguageDropDown button").ClickAsync();

    // Wait for Alpine.js animation
    await Page.WaitForSelectorAsync("#LanguageDropDown div[x-show]", new()
    {
        State = WaitForSelectorState.Visible
    });

    // Check dropdown is visible
    var isVisible = await Page.Locator("#LanguageDropDown div[x-show]").IsVisibleAsync();
    Assert.True(isVisible);

    // Click outside to close
    await Page.Locator("body").ClickAsync(new LocatorClickOptions
    {
        Position = new Position { X = 0, Y = 0 }
    });

    // Verify closed
    await Page.WaitForSelectorAsync("#LanguageDropDown div[x-show]", new()
    {
        State = WaitForSelectorState.Hidden
    });

    isVisible = await Page.Locator("#LanguageDropDown div[x-show]").IsVisibleAsync();
    Assert.False(isVisible);
}

Forme di prova con convalida

[Fact]
public async Task CommentForm_ValidatesRequiredFields()
{
    await NavigateAsync("/blog/some-post");

    // Try to submit without filling fields
    await Page.Locator("#comment-submit").ClickAsync();

    // Check HTML5 validation messages
    var nameInput = Page.Locator("#comment-name");
    var validationMessage = await nameInput.EvaluateAsync<string>("el => el.validationMessage");

    Assert.NotEmpty(validationMessage);
    Output.WriteLine($"Validation message: {validationMessage}");

    // Fill form properly
    await nameInput.FillAsync("Test User");
    await Page.Locator("#comment-email").FillAsync("[email protected]");
    await Page.Locator("#comment-content").FillAsync("Great article!");

    // Submit
    await Page.Locator("#comment-submit").ClickAsync();

    // Wait for success
    await Page.Locator(".comment-success").WaitForAsync();
}

Caratteristiche avanzate di Playwright

Intercezione di rete - più potente di PuppeteerSharp

[Fact]
public async Task PageLoadsWithoutImages_ToTestPerformance()
{
    // Block all image requests
    await Page.RouteAsync("**/*.{png,jpg,jpeg,gif,webp}", route => route.AbortAsync());

    await NavigateAsync("/blog");

    // Page should still function without images
    var title = await Page.Locator("h1").TextContentAsync();
    Assert.NotEmpty(title);
}

[Fact]
public async Task MockAPIResponse_ForTesting()
{
    // Intercept API calls and return mock data
    await Page.RouteAsync("**/api/posts", route => route.FulfillAsync(new()
    {
        Status = 200,
        ContentType = "application/json",
        Body = System.Text.Json.JsonSerializer.Serialize(new
        {
            posts = new[]
            {
                new { id = 1, title = "Mock Post 1" },
                new { id = 2, title = "Mock Post 2" }
            }
        })
    }));

    await NavigateAsync("/blog");

    // Should show mock data
    var posts = await Page.Locator(".post-title").CountAsync();
    Assert.Equal(2, posts);
}

Trace Viewer - Debug dei test non riuscito

public async Task InitializeAsync()
{
    Playwright = await Microsoft.Playwright.Playwright.CreateAsync();
    Browser = await LaunchBrowserAsync();

    // Start tracing
    Context = await Browser.NewContextAsync();
    await Context.Tracing.StartAsync(new()
    {
        Screenshots = true,
        Snapshots = true,
        Sources = true
    });

    Page = await Context.NewPageAsync();
}

public async Task DisposeAsync()
{
    // Save trace on test completion
    var tracePath = Path.Combine("traces", $"{TestContext.TestName}.zip");
    await Context.Tracing.StopAsync(new()
    {
        Path = tracePath
    });

    // View trace with: playwright show-trace traces/TestName.zip

    await Page?.CloseAsync()!;
    await Context?.CloseAsync()!;
    await Browser?.CloseAsync()!;
    Playwright?.Dispose();
}

Poi visionare la traccia:

playwright show-trace traces/TestName.zip

Questo apre un'interfaccia utente che mostra:

  • Ogni azione che il tuo test ha fatto
  • Schermate ad ogni passo
  • Richieste di rete
  • Tronchi console
  • Istantanee DOM

E' assolutamente geniale per il debugging.

Schermate sul fallimento

public async Task DisposeAsync()
{
    // Take screenshot if test failed
    if (TestContext.CurrentTestOutcome != TestOutcome.Passed)
    {
        var screenshot = await Page.ScreenshotAsync();
        File.WriteAllBytes($"failure-{TestContext.TestName}.png", screenshot);
        Output.WriteLine($"Screenshot saved: failure-{TestContext.TestName}.png");
    }

    await Page?.CloseAsync()!;
    await Context?.CloseAsync()!;
    await Browser?.CloseAsync()!;
    Playwright?.Dispose();
}

Emulazione mobile

[Fact]
public async Task BlogPage_WorksOnMobile()
{
    // Create context with mobile emulation
    var iPhone = Playwright.Devices["iPhone 13"];
    await using var context = await Browser.NewContextAsync(iPhone);
    await using var page = await context.NewPageAsync();

    await page.GotoAsync($"{BaseUrl}/blog");

    // Check mobile menu is visible
    var mobileMenu = page.Locator(".mobile-menu");
    await Expect(mobileMenu).ToBeVisibleAsync();

    // Desktop menu should be hidden
    var desktopMenu = page.Locator(".desktop-menu");
    await Expect(desktopMenu).Not.ToBeVisibleAsync();
}

Playwright viene fornito con descrittori di dispositivi anziché:

  • iPhone 13, 13 Pro, 12, 11, SE
  • iPad, iPad Pro
  • Samsung Galaxy, Pixel
  • E molti altri

Prova della modalità scura

[Fact]
public async Task DarkMode_TogglesCorrectly()
{
    // Start with dark color scheme
    await using var context = await Browser.NewContextAsync(new()
    {
        ColorScheme = ColorScheme.Dark
    });
    await using var page = await context.NewPageAsync();

    await page.GotoAsync($"{BaseUrl}");

    // Check dark mode is active
    var isDark = await page.EvaluateAsync<bool>(
        "() => window.matchMedia('(prefers-color-scheme: dark)').matches"
    );
    Assert.True(isDark);

    // Check background color reflects dark mode
    var bgColor = await page.Locator("body").EvaluateAsync<string>(
        "el => getComputedStyle(el).backgroundColor"
    );
    Assert.Contains("rgb(0, 0, 0)", bgColor); // Dark background
}

Playwright vs PuppeteerSharp - Side by Side

Ecco lo stesso test in entrambe le librerie per mostrare le differenze:

Versione PuppeteerSharp

[Fact]
public async Task FilterTest_PuppeteerSharp()
{
    await Page.GoToAsync("http://localhost:8080/blog");

    // Manual waiting required
    await Page.WaitForSelectorAsync("#LanguageDropDown button");
    await Page.ClickAsync("#LanguageDropDown button");

    // Wait for dropdown animation
    await Task.Delay(300);

    // Click Spanish option
    await Page.WaitForSelectorAsync("#LanguageDropDown li:nth-child(2) a");
    await Page.ClickAsync("#LanguageDropDown li:nth-child(2) a");

    // Wait for navigation
    await Task.Delay(500);

    // Check URL
    var url = Page.Url;
    Assert.Contains("language=", url);
}

Versione Playwright

[Fact]
public async Task FilterTest_Playwright()
{
    await Page.GotoAsync("http://localhost:8080/blog");

    // Auto-waiting built in
    await Page.Locator("#LanguageDropDown button").ClickAsync();

    // Click Spanish option (waits automatically for visibility)
    await Page.Locator("#LanguageDropDown li:has-text('Spanish')").ClickAsync();

    // Check URL (waits automatically for navigation)
    await Expect(Page).ToHaveURLAsync(new Regex(".*language=.*"));
}

Avviso:

  • Nessun manuale WaitForSelectorAsync necessario
  • No. Task.Delay necessario
  • Asserzioni più pulite con Expect
  • Più leggibile con has-text selettore

Generazione PDF con Playwright

Come PuppeteerSharp, Playwright può generare PDF. L'API è quasi identica:

public async Task<byte[]> GeneratePdfAsync(string url)
{
    await using var browser = await Playwright.Chromium.LaunchAsync();
    await using var page = await browser.NewPageAsync();
    await page.GotoAsync(url);

    return await page.PdfAsync(new()
    {
        Format = "A4",
        PrintBackground = true,
        Margin = new()
        {
            Top = "20mm",
            Right = "20mm",
            Bottom = "20mm",
            Left = "20mm"
        }
    });
}

Lo stesso PDF ottenutochas dall'articolo PuppeteerSharp applicare anche qui.

Quando scegliere Playwright

graph TD
    A[Need E2E Testing?] --> B{Multi-browser required?}
    B -->|Yes| C[Playwright]
    B -->|No| D{Chrome only?}
    D -->|Yes| E[PuppeteerSharp or Playwright]
    D -->|No| C

    C --> F[Benefits]
    F --> F1[Test all major browsers]
    F --> F2[Better debugging tools]
    F --> F3[More reliable waiting]
    F --> F4[Mobile emulation]

    E --> G[PuppeteerSharp Benefits]
    G --> G1[Simpler setup]
    G --> G2[Smaller overhead]
    G --> G3[Chromium focused]

    style C stroke:#00aa00,stroke-width:3px
    style E stroke:#0066cc,stroke-width:2px

Scegliere Playwright quando:

  • Hai bisogno di test multi-browser
  • Vuoi strumenti di debug migliori (Visualizzatore traccia)
  • Stai testando complesse applicazioni web moderne
  • Hai bisogno di emulazione mobile
  • Vuoi test più affidabili fuori dalla scatola

Scegliere PuppeteerSharp quando:

  • Chrome / Bordo solo va bene
  • Vuoi una configurazione più semplice
  • Conosci già Puppeteer.
  • Hai bisogno di un po 'meno risorse in alto

Esecuzione in CI/CD

Esempio di azioni GitHub

Playwright funziona senza soluzione di continuità in pipeline CI/CD. Ecco un completo Azioni GitHub flusso di lavoro:

name: Playwright Tests

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3

    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: '9.0.x'

    - name: Install dependencies
      run: dotnet restore

    - name: Build
      run: dotnet build --no-restore

    - name: Install Playwright browsers
      run: pwsh Mostlylucid.Test/bin/Debug/net9.0/playwright.ps1 install --with-deps

    - name: Start application
      run: |
        dotnet run --project Mostlylucid/Mostlylucid.csproj &
        echo $! > app.pid

    - name: Wait for application
      run: |
        timeout 60 bash -c 'until curl -f http://localhost:8080/health; do sleep 2; done'

    - name: Run Playwright tests
      run: |
        dotnet test Mostlylucid.Test/Mostlylucid.Test.csproj \
          --filter "Category=E2E" \
          --logger "console;verbosity=detailed"

    - name: Upload test results
      if: always()
      uses: actions/upload-artifact@v3
      with:
        name: playwright-results
        path: |
          **/test-results/
          **/traces/

    - name: Stop application
      if: always()
      run: kill $(cat app.pid) || true

Supporto docker

Eseguire test Playwright in DockerCity name (optional, probably does not need a translation) richiede l'installazione di dipendenze di sistema:

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build

# Install Playwright dependencies
RUN apt-get update && apt-get install -y \
    libnss3 \
    libnspr4 \
    libatk1.0-0 \
    libatk-bridge2.0-0 \
    libcups2 \
    libdrm2 \
    libxkbcommon0 \
    libxcomposite1 \
    libxdamage1 \
    libxfixes3 \
    libxrandr2 \
    libgbm1 \
    libasound2

WORKDIR /app
COPY . .

RUN dotnet restore
RUN dotnet build
RUN pwsh Mostlylucid.Test/bin/Debug/net9.0/playwright.ps1 install

CMD ["dotnet", "test"]

Confronto delle prestazioni

Dal mio test su questo blog:

Caratteristiche Condivisione del puppeteer Playwright
Velocità di prova cromata ~2.5s ~2.8s
Multi-browser (aggiunge ~1s per browser) (Aggiungi ~1s per browser)
Affidabilità in attesa automatica Buono (manuale) Eccellente (automatico)
Memoria per browser ~ 150MB ~ 180MB
Complessità di configurazione Semplice Moderate
Strumenti di debug DevTools cromato Trace Viewer + DevTools
Emulazione mobile Base Eccellente

Playwright è leggermente più lento e utilizza un po 'più di memoria, ma l'affidabilità e i vantaggi di debug di solito superano questo.

Common GotchasCity name (optional, probably does not need a translation)

1. Modalità rigida

I localizzatori di Playwright sono severi per impostazione predefinita:

// This errors if multiple buttons exist
await Page.Locator("button").ClickAsync();

// Be specific
await Page.Locator("button#submit").ClickAsync();

// Or use .First if you really want the first match
await Page.Locator("button").First.ClickAsync();

2. Installazione del browser

Non dimenticare di correre playwright install dopo aver aggiunto il pacchetto. I browser non sono inclusi nel pacchetto NuGet.

3. Contesto e pagina

Ricorda i contesti di prova isolati:

// Bad - state leaks between tests
await Page.GotoAsync("/login");
// Do stuff...
await Page.GotoAsync("/dashboard");
// Previous login state might still exist

// Good - fresh context per test
await using var context = await Browser.NewContextAsync();
await using var page = await context.NewPageAsync();
// Completely isolated

4. Differenze Webkit

Safari (WebKit) può comportarsi in modo diverso:

// May work in Chrome but fail in WebKit
await Page.Locator(".dropdown").Hover();
await Page.Locator(".dropdown-item").ClickAsync();

// More reliable across browsers
await Page.Locator(".dropdown").ClickAsync();
await Page.WaitForSelectorAsync(".dropdown-item");
await Page.Locator(".dropdown-item").ClickAsync();

Conclusione

Playwright rappresenta l'evoluzione dell'automazione del browser per gli sviluppatori .NET. Se avete bisogno di supporto multi-browser, è la scelta chiara. Sì, è leggermente più complessa di PuppeteerSharp, ma i benefici sono sostanziali:

  • Prova su tutti i principali browser con codice identico
  • Migliore affidabilità con l'attesa automatica
  • Eccellente debug con visore traccia
  • Emulazione mobile e tablet fuori dalla scatola
  • Più resiliente ai problemi di temporizzazione

La mia raccomandazione:

  • Nuovi progetti che necessitano di test cross-browser: Inizia con Playwright
  • Progetti solo Chrome: PuppeteerSharp è più semplice
  • Progetti PuppeteerSharp esistenti: Migra solo se hai bisogno di più browser
  • Complesso di applicazioni web moderne: L'attrezzatura di Playwright vale la pena

Il visualizzatore traccia da solo mi ha salvato ore di debug. Essere in grado di riprodurre un test fallito e vedere esattamente ciò che il browser ha visto ad ogni passo è inestimabile.

Dare Playwright un andare sul tuo prossimo progetto - sarete piacevolmente sorpresi quanto più facile rende cross-browser testing.

Ulteriore lettura

logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.