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 .csproj
file removing the Version
tag from the Microsoft.AspNetCore.App
package reference and change the Sdk
property of the root to Microsoft.NET.Sdk.Web
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.
- You can write a
SetUpFixture
which creates your application once and is used throughout all the tests - Each set of tests can have a
OneTimeSetUp
which do the same thing - 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 OneTimeSetUp
you create a new factory and then an HttpClient
from that. In the OneTimeTearDown
remember to dispose.
That’s all there is to it, happy testing!