Unit Testing with xUnit.net in ASP.NET Core 2.0



Last updated: January 28th, 2024

Why Write Unit Tests?

Unit testing is a fast way to test code automatically before releasing it to production. Unlike other testing, unit tests should be designed to run in milliseconds, without any external dependencies. Without running unit tests, there is a chance for regression in code and that means unexpected bugs.

Why xUnit.net?

Using xUnit.net is a choice I made because it's free, open source and is supported by the .NET Foundation.

I wanted to use it instead of MSTest because it offers a more useful syntax when testing multiple scenarios in a single method. For example. you can have attributes on your method that reuse the same method with xUnit.net Theories.

Example:

How To Add xUnit.net To A Solution

Adding an xUnit.net project is easy in Visual Studio 2017 when using .NET Core. You just right click on your project, add a new project and find the "xUnit Test Project (.NET Core)".

Once you have the project, you can add a test runner to run the tests in Visual Studio. To do that, install the "xunit.runner.console" and "xunit.runner.visualstudio" xUnit NuGet packages.

Running xUnit.net Tests From The Command Line

Everything must be able to be automated to work in a continuous deployment release process. With xUnit.net, running the tests is quite easy. You simply run a single command and optionally specify the path to the unit test project, if not currently in that directory.

Example:

This will output the results of your test run to the console.


Comments

No Comments

Post Comment

Prove you are human 10 + 7 =



Join my email list!



ryan
About Me

With over 15 years in tech, I've excelled as a senior software engineer, specializing in ASP.NET, C#, SQL, Azure, and front-end technologies. I've led diverse projects across various sectors, from startups to global corporations, particularly during my decade in the San Francisco Bay Area.


Sign Up With SoftSys Hosting! (My host)