Automated UI testing

Publish date: 12 Jun 2021
Tags: software, tools

Finally got around to using Playwright - a tool for UI testing. The official documentation is here https://playwright.dev/ .

I am using C# and Microsoft has a nuget package. I also wanted to use it in a NUnit project.

The two sites that helped me get started were :

Create a new NUnit project in VS2019 (make sure you use .NET 5 and above). Add the Playwright NuGet package.

Use this command to startup the Recorder, which is a neat way to capture your navigation

CMD> npx playwright codegen <url_you_want_to_test>

Copy the generated code ( C# in my case) from the Recorder clipboard and paste into your C# Test project. Any build errors should be straight forward to fix. In my case I created a simple console application.

using System.IO;
using System.Threading.Tasks;

using Microsoft.Playwright;

namespace ConsoleApp1
{
    class Program
    {
        public static async Task Main()
        {
            using var playwright = await Playwright.CreateAsync();
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = false,
            });
            var context = await browser.NewContextAsync();

            // Open new page
            var page = await context.NewPageAsync();

            // Go to https://www.richardborges.net/
            await page.GotoAsync("https://www.richardborges.net/");

            // Click text=Increasing Productivity
            await page.ClickAsync("text=Increasing Productivity");
            // Assert.Equal("https://www.richardborges.net/2021-05-30-increasing-productivity/", page.Url);

            // Click text=Blog
            await page.ClickAsync("text=Blog");
            // Assert.Equal("https://www.richardborges.net/", page.Url);

            // Click text=Richard Borges
            await page.ClickAsync("text=Richard Borges");

            // Click text=About
            await page.ClickAsync("text=About");
            // Assert.Equal("https://www.richardborges.net/about/", page.Url);

            // Click text=Blog
            await page.ClickAsync("text=Blog");
            // Assert.Equal("https://www.richardborges.net/", page.Url);

            await File.WriteAllBytesAsync(Path.Combine(Directory.GetCurrentDirectory(), "richardborges.net.png"),   await page.ScreenshotAsync());
        }
    }
}

I could also create a NUnit project and assert my test conditions. The method

File.WriteAllBytesAsync(...)

will save a screen shot of the test page. The test can be run with a headless browser as well.