Getting Tests Setup Quickly in .NET Core
Testing in .NET Core is extremely easy with xunit but the setup process for those of us outside of Visual Studio can be a bit trickier. In this post I will cover setting up all of the packages and getting a demo test running.
The .NET landscape is a big place and there are a lot of ways to do development. This post is targetted at the following people:
- who want to run tests in the same project as their application
- are on .NET Core 1.1
- are using the CLI instead of Visual Studio
- VS Code as your editor counts as CLI
At the time of publishing, only .NET Core apps are supported for running tests. So, if you want to run tests in your library project it will require a separate project for running tests. I won’t be going through that here.
To check your target framework, open your
.csproj and look for
something similar to this line
The important part here is
These are the packages that will get your tests going:
You can install these by running the following commands
Now you will need to run a
dotnet restore and
dotnet build. For safety. I think.
If you like having your tests run on every change, add this to your
dotnet restore so that your watcher gets installed. You will
now have access to
dotnet watch -h.
Ask dotnet not to generate a Program.cs
Prior to creating any tests, we’re going to add a line to the
What it does is avoid an error when tests are run later by asking the test
framework to not add a
Program.cs. In the
csproj file, look for
<PropertyGroup>, add the following line:
I’ll be honest, Andrew Lock has done all the hardwork on figuring out what causes an error and why. I definitely suggest you checkout his post: Fixing the error “Program has more than one entry point defined” for console apps containing xUnit tests.
Create a test test
Now lets create a simple test. The file can be placed anywhere
as xunit should look for
You can learn more abour writing tests from the xunit documentation.
The moment of truth! Hop over to your console and run
dotnet test or
dotnet watch test. You should see output
that looks similar to this:
Build started, please wait... Build completed. Test run for D:\AProjectName\bin\Debug\netcoreapp1.1\AProjectName.dll(.NETCoreApp,Version=v1.1) Microsoft (R) Test Execution Command Line Tool Version 18.104.22.168 Copyright (c) Microsoft Corporation. All rights reserved. Starting test execution, please wait... [xUnit.net 00:00:00.7076855] Discovering: AProjectName [xUnit.net 00:00:00.8317487] Discovered: AProjectName [xUnit.net 00:00:00.8899867] Starting: AProjectName [xUnit.net 00:00:01.0408994] Finished: AProjectName Total tests: 1. Passed: 1. Failed: 0. Skipped: 0. Test Run Successful. Test execution time: 1.9250 Seconds
Tests are executing!
As I mentioned earlier, .NET is a big place. Here are a few resources I used to get this post together and so that you can build more complex setups for your projects.