C#: Create an XUnit test project in 2 minutes

Date: 2021-01-11 | csharp | xunit | dotnet-core |

Overview

Any sufficiently large codebase will need testing. Pretty much every codebase should have testing. I've been building a lot with C# recently and wanted to create a super simple, repeatable process for getting up and running with an XUnit test project.

Here's my process for creating an XUnit test project in 2 minutes.

Create an XUnit Test Project

I use dotnet core and I'm going to assume that I already have a project MyProject created in directory MyProject. So looking at a directory view, we'd have something like:

./ (we are here)
- MyProject

Let's create an XUnit test project called MyTests by running these commands from a terminal:

  • mkdir MyTests - create the directory for MyTests
  • cd MyTests - navigate into directory
  • dotnet new xunit - create our xunit project
  • dotnet test - test that everything's working alright

If everything succeeded you should see outputs saying that your tests passed. Your directory should now look something like:

./ (we are here)
- MyProject
- MyTests

Reference your project from tests

So now we have a test project that we can run. Usually you'll want to test code from another project (like MyProject) and we're not quite ready for that. If we try to test code from MyProject right now MyTests will throw errors saying it doesn't know what that code is. That's because we haven't given MyTests a reference to MyProject and thus it can't figure out what the imported code is.

To add a reference to MyProject you can use the add reference command:

dotnet add PATH_TO_CSPROJ reference PATH_TO_REFERENCE_CSPROJ

In our case we'll want MyTests to reference MyProject because we'd like to use our source code inside of our tests. So here we'd run something like:

dotnet add ./MyTests/MyTests.csproj reference ./MyProject/MyProject.csproj

Fin

Assuming everything worked correctly you should now have a working xunit project!

Happy coding!

-HAMY.OUT

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.