• About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us
AimactGrow
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing
No Result
View All Result
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing
No Result
View All Result
AimactGrow
No Result
View All Result

Updating to .NET 8, updating to IHostBuilder, and working Playwright Assessments inside NUnit headless or headed on any OS

Admin by Admin
March 31, 2025
Home Coding
Share on FacebookShare on Twitter



All the Unit Tests passI have been doing not simply Unit Testing for my websites however full on Integration Testing and Browser Automation Testing as early as 2007 with Selenium. These days, nonetheless, I have been utilizing the sooner and usually extra suitable Playwright. It has one API and might take a look at on Home windows, Linux, Mac, domestically, in a container (headless), in my CI/CD pipeline, on Azure DevOps, or in GitHub Actions.

For me, it is that final second of fact to make it possible for the location runs fully from finish to finish.

I can write these Playwright checks in one thing like TypeScript, and I may launch them with node, however I like working finish unit checks and utilizing that take a look at runner and take a look at harness as my leaping off level for my .NET purposes. I am used to proper clicking and “run unit checks” and even higher, proper click on and “debug unit checks” in Visible Studio or VS Code. This will get me the good thing about the entire assertions of a full unit testing framework, and all the advantages of utilizing one thing like Playwright to automate my browser.

In 2018 I used to be utilizing WebApplicationFactory and a few tough hacks to mainly spin up ASP.NET inside .NET (on the time) Core 2.1 inside the unit checks after which launching Selenium. This was sort of janky and would require to manually begin a separate course of and handle its life cycle. Nevertheless, I saved on with this hack for a variety of years mainly attempting to get the Kestrel Net Server to spin up within my unit checks.

I’ve lately upgraded my foremost web site and podcast web site to .NET 8. Remember the fact that I have been transferring my web sites ahead from early early variations of .NET to the latest variations. The weblog is fortunately working on Linux in a container on .NET 8, however its unique code began in 2002 on .NET 1.1.

Now that I am on .NET 8, I scandalously found (as my unit checks stopped working) that the remainder of the world had moved from IWebHostBuilder to IHostBuilder 5 model of .NET in the past. Gulp. Say what you’ll, however the backward compatibility is spectacular.

As such my code for Program.cs modified from this

public static void Essential(string[] args)
{
CreateWebHostBuilder(args).Construct().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup();

to this:

public static void Essential(string[] args)
{
CreateHostBuilder(args).Construct().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).
ConfigureWebHostDefaults(WebHostBuilder => WebHostBuilder.UseStartup());

Not a serious change on the surface however tidies issues up on the within and units me up with a extra versatile generic host for my net app.

My unit checks stopped working as a result of my Kestral Net Server hack was not firing up my server.

Right here is an instance of my objective from a Playwright perspective inside a .NET NUnit take a look at.

[Test]
public async Job DoesSearchWork()
{
await Web page.GotoAsync(Url);

await Web page.Locator("#topbar").GetByRole(AriaRole.Hyperlink, new() { Title = "episodes" }).ClickAsync();

await Web page.GetByPlaceholder("search and filter").ClickAsync();

await Web page.GetByPlaceholder("search and filter").TypeAsync("spouse");

const string visibleCards = ".showCard:seen";

var ready = await Web page.WaitForSelectorAsync(visibleCards, new PageWaitForSelectorOptions() { Timeout = 500 });

await Count on(Web page.Locator(visibleCards).First).ToBeVisibleAsync();

await Count on(Web page.Locator(visibleCards)).ToHaveCountAsync(5);
}

I really like this. Good and clear. Definitely right here we’re assuming that we’ve got a URL in that first line, which can be localhost one thing, after which we assume that our net software has began up by itself.

Right here is the setup code that begins my new “net software take a look at builder manufacturing facility,” yeah, the title is silly however it’s descriptive. Observe the OneTimeSetUp and the OneTimeTearDown. This begins my net app inside the context of my TestHost. Observe the :0 makes the app discover a port which I then, sadly, must dig out and put into the Url personal to be used inside my Unit Assessments. Observe that the is in reality my Startup class inside Startup.cs which hosts my app’s pipeline and Configure and ConfigureServices get setup right here so routing all works.

personal string Url;
personal WebApplication? _app = null;

[OneTimeSetUp]
public void Setup()
{
var builder = WebApplicationTestBuilderFactory.CreateBuilder();

var startup = new Startup(builder.Surroundings);
builder.WebHost.ConfigureKestrel(o => o.Pay attention(IPAddress.Loopback, 0));
startup.ConfigureServices(builder.Companies);
_app = builder.Construct();

// hear on any native port (therefore the 0)
startup.Configure(_app, _app.Configuration);
_app.Begin();

//you might be kidding me
Url = _app.Companies.GetRequiredService().Options.GetRequiredFeature().Addresses.Final();
}

[OneTimeTearDown]
public async Job TearDown()
{
await _app.DisposeAsync();
}

So what horrors are buried in WebApplicationTestBuilderFactory? The primary bit is unhealthy and we must always repair it for .NET 9. The remaining is definitely each good, with a hat tip to David Fowler for his assist and steering! That is the magic and the ick in a single small helper class.

public class WebApplicationTestBuilderFactory 
{
public static WebApplicationBuilder CreateBuilder() the place T : class
{
//This ungodly code requires an unused reference to the MvcTesting package deal that hooks up
// MSBuild to create the manifest file that's learn right here.
var testLocation = Path.Mix(AppContext.BaseDirectory, "MvcTestingAppManifest.json");
var json = JsonObject.Parse(File.ReadAllText(testLocation));
var asmFullName = typeof(T).Meeting.FullName ?? throw new InvalidOperationException("Meeting Full Title is null");
var contentRootPath = json?[asmFullName]?.GetValue();

//spin up an actual reside net software inside TestHost.exe
var builder = WebApplication.CreateBuilder(
new WebApplicationOptions()
{
ContentRootPath = contentRootPath,
ApplicationName = asmFullName
});
return builder;
}
}

The primary 4 traces are nasty. As a result of the take a look at runs within the context of a distinct listing and my web site must run inside the context of its personal content material root path, I’ve to drive the content material root path to be appropriate and the one approach to do this is by getting the apps base listing from a file generated inside MSBuild from the (growing old) MvcTesting package deal. The package deal will not be used, however by referencing it it will get into the construct and makes that file that I then use to tug out the listing.

If we will do away with that “hack” and pull the listing from context elsewhere, then this helper operate turns right into a single line and .NET 9 will get WAY WAY extra testable!

Now I can run my Unit Assessments AND Playwright Browser Integration Assessments throughout all OS’s, headed or headless, in docker or on the steel. The location is up to date to .NET 8 and all is true with my code. Effectively, it runs at the least. 😉




About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, advisor, father, diabetic, and Microsoft worker. He’s a failed stand-up comedian, a cornrower, and a e-book writer.

facebook
bluesky
subscribe
About   E-newsletter

Internet hosting By
Hosted on Linux using .NET in an Azure App Service








Tags: .NETheadedheadlessIHostBuilderNUnitPlaywrightrunningTestsUpdating
Admin

Admin

Next Post
One Of 2024’s Most Fashionable Video games Is Free On PS Plus For The Subsequent 24 Hours

One Of 2024's Most Fashionable Video games Is Free On PS Plus For The Subsequent 24 Hours

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recommended.

DemandJen’s Outreach Ideas [+ Video]

DemandJen’s Outreach Ideas [+ Video]

June 14, 2025
A Minecraft Film Is A Dangerous Film Made Worse By Jack Black

A Minecraft Film Is A Dangerous Film Made Worse By Jack Black

April 9, 2025

Trending.

Industrial-strength April Patch Tuesday covers 135 CVEs – Sophos Information

Industrial-strength April Patch Tuesday covers 135 CVEs – Sophos Information

April 10, 2025
Expedition 33 Guides, Codex, and Construct Planner

Expedition 33 Guides, Codex, and Construct Planner

April 26, 2025
How you can open the Antechamber and all lever places in Blue Prince

How you can open the Antechamber and all lever places in Blue Prince

April 14, 2025
Important SAP Exploit, AI-Powered Phishing, Main Breaches, New CVEs & Extra

Important SAP Exploit, AI-Powered Phishing, Main Breaches, New CVEs & Extra

April 28, 2025
Wormable AirPlay Flaws Allow Zero-Click on RCE on Apple Units by way of Public Wi-Fi

Wormable AirPlay Flaws Allow Zero-Click on RCE on Apple Units by way of Public Wi-Fi

May 5, 2025

AimactGrow

Welcome to AimactGrow, your ultimate source for all things technology! Our mission is to provide insightful, up-to-date content on the latest advancements in technology, coding, gaming, digital marketing, SEO, cybersecurity, and artificial intelligence (AI).

Categories

  • AI
  • Coding
  • Cybersecurity
  • Digital marketing
  • Gaming
  • SEO
  • Technology

Recent News

The Obtain: tackling tech-facilitated abuse, and opening up AI {hardware}

The Obtain: tackling tech-facilitated abuse, and opening up AI {hardware}

June 18, 2025
Why Media Coaching is Vital for Danger Administration and Model Status

Why Media Coaching is Vital for Danger Administration and Model Status

June 18, 2025
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us

© 2025 https://blog.aimactgrow.com/ - All Rights Reserved

No Result
View All Result
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing

© 2025 https://blog.aimactgrow.com/ - All Rights Reserved