Using WebApplicationFactory with NUnit

WebApplicationFactory was one of really cool features of ASP.NET Core 2 when it released. It meant that you didn’t have to write a lot of code to spin up a integration test server yourself and can instead focus on writing the actual tests.

Unfortunately, all of the documentation written for it was with xUnit. I do quite like xUnit but not everybody uses it and it does work very differently to the other major .NET testing frameworks.

Thankfully getting The WebApplicationFactory working is simple enough.

To start off, you’ll need to have a Web App created with a Startup. I imagine if you are reading this you have already created it (especially as it’s in every new starter template for Web Apps).

Next, create a Test project for NUnit. You can either do this through the GUI or through the dotnet cli

If you don’t have the templates, you may need to install them with the first command below.

dotnet new -i NUnit3.DotNetNew.Templatedotnet new nunit --framework netcoreapp2.2

Now you will need to install some NuGet Packages in that project.

Microsoft.AspNetCore.AppMicrosoft.AspNetCore.Mvc.Testing

Finally, edit the file removing the tag from the package reference and change the property of the root to

It should look something like the following

With your new test project now set up, create a file for that will inherit from WebApplicationFactory. In this example, I’m going to assume it’s an API of some sort.

Finally, you can write your test. Now there are a few ways of going about this.

  1. You can write a which creates your application once and is used throughout all the tests
  2. Each set of tests can have a which do the same thing
  3. A mix of the two!

For this scenario I’m just going to demonstrate the second but if you’re familiar with NUnit it should be very easy to adapt.

The key parts here being in the set up and tear down.

In the you create a new factory and then an from that. In the remember to dispose.

That’s all there is to it, happy testing!

--

--

I’m a dotnet developer who currently is working at Commify. I also unfortunately like Ipswich Town football club. It’s a shame they aren’t very good.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniel Edwards

I’m a dotnet developer who currently is working at Commify. I also unfortunately like Ipswich Town football club. It’s a shame they aren’t very good.