In a previous post, I wrote about testing an ASP.NET Core application with an in-memory server. This is useful to run integration tests to validate the server produces the expected response for a request. However, this doesn’t allow to test JavaScript code nor to validate how the page displays. If you want to test these components, you need to run an actual browser and load your site. The code in this post allows to test ASP.NET Core MVC application and ASP.NET Core Blazor Server application.

There are multiple ways to instrument browsers. The most used library is Selenium. This library uses the WebDriver, a W3C recommandation. The WebDriver API is implementated by all major browsers, so this is the way to use when you need to support many browsers. Pupeteer and Playwright came out more recently and provide similar automation capabilities with a simplier API and more control on the browsers, but they support less browsers. Playwright only supports Chromium, Firefox and WebKit browsers.

In this post, I’ll use Playwright as it comes with nice helpers to install all dependencies and there is a .NET wrapper. The .NET wrapper is developed by Dario Kondratiuk. The repository recently moved to the microsoft organization.

#Starting the server in the unit tests

To test with a browser, you need to start the web server and get its URL. ASP.NET Core doesn’t come with a ready to use API to do that in your tests. You can upvote this issue if you think this is could be useful. That’s being said, the ASP.NET Core repository on GitHub contains samples in their tests that can be reused. That’s what is nice when you use an OSS product 😃

First, add a reference to the Microsoft.AspNetCore.Mvc.Testing NuGet package to your project:

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.8" />
</ItemGroup>

#asp.net core #.net #web

Writing automated UI tests for an ASP.NET Core application using Playwright and xUnit
12.90 GEEK