|
| 1 | +using Microsoft.Playwright; |
| 2 | +using NUnit.Framework; |
| 3 | + |
| 4 | +namespace Playwright.NUnit.Testing.Base; |
| 5 | + |
| 6 | +public class TestBase(BrowserKind kind) { |
| 7 | + protected readonly BrowserKind _kind = kind; |
| 8 | + |
| 9 | + private IPlaywright _pw = default!; |
| 10 | + private IBrowser _browser = default!; |
| 11 | + private IBrowserContext _context = default!; |
| 12 | + protected IPage Page = default!; |
| 13 | + |
| 14 | + [OneTimeSetUp] |
| 15 | + public async Task OneTimeSetUpAsync() { |
| 16 | + _pw = await Microsoft.Playwright.Playwright.CreateAsync(); |
| 17 | + |
| 18 | + var launch = new BrowserTypeLaunchOptions { |
| 19 | + Headless = true, // flip to false to watch the run |
| 20 | + Args = ["--no-sandbox"] // helpful in some CI agents |
| 21 | + }; |
| 22 | + |
| 23 | + _browser = _kind switch { |
| 24 | + BrowserKind.Chromium => await _pw.Chromium.LaunchAsync(launch), |
| 25 | + BrowserKind.Firefox => await _pw.Firefox.LaunchAsync(launch), |
| 26 | + BrowserKind.WebKit => await _pw.Webkit.LaunchAsync(launch), |
| 27 | + _ => throw new AssertionException($"Unknown browser: {_kind}") |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + [SetUp] |
| 32 | + public async Task SetUpAsync() { |
| 33 | + // Fresh, isolated state per test |
| 34 | + _context = await _browser.NewContextAsync(new BrowserNewContextOptions { |
| 35 | + ViewportSize = new ViewportSize { Width = 1280, Height = 800 } |
| 36 | + }); |
| 37 | + Page = await _context.NewPageAsync(); |
| 38 | + } |
| 39 | + |
| 40 | + [TearDown] |
| 41 | + public async Task TearDownAsync() { |
| 42 | + if(_context is not null) { |
| 43 | + await _context.CloseAsync(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + [OneTimeTearDown] |
| 48 | + public async Task OneTimeTearDownAsync() { |
| 49 | + if(_browser is not null) { |
| 50 | + await _browser.CloseAsync(); |
| 51 | + } |
| 52 | + _pw?.Dispose(); |
| 53 | + } |
| 54 | +} |
0 commit comments