I've written a Playwright test but instead of running it via the test runner (NUnit), I'd like to run my Playwright code either from a console application or an ASP.NET Core background service.
What is the easiest way to setup Playwright so that it can be run without a test runner?
This is my current console app code:
using Microsoft.Playwright;
var browserTest = new Microsoft.Playwright.NUnit.BrowserTest();
var context = await browserTest.NewContext();
var page = await context.NewPageAsync();
await page.SetViewportSizeAsync(600,800);
await page.GotoAsync("https://www.google.com/");
...raising a NullReferenceException
for await browserTest.NewContext();
.
I'm using:
The console app has to reference the NuGet package Microsoft.Playwright.NUnit
and must run the following startup code:
var pageTest = new PageTest();
pageTest.WorkerSetup();
await pageTest.PlaywrightSetup();
await pageTest.BrowserSetup();
await pageTest.ContextSetup();
await pageTest.PageSetup();
var page = pageTest.Page;
Then you can do the regular Playwright stuff:
await page.SetViewportSizeAsync(600, 800);
await page.GotoAsync("https://www.google.com/");
Even easier, as @max-schmitt pointed out via the official docs: reference the NuGet package Microsoft.Playwright
and instantiate Playwright like this:
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();