.Net Core Side-By-Side Unit Tests with Code Coverage

Michael J. Ryan
2 min readDec 3, 2019

One of my own, personal niggles with .Net Core defaults is that you will usually create a separate project to create your tests. So I set out to create a project that included xUnit tests as well as worked for Code Coverage.

Photo by Christopher Gower on Unsplash

Once you create your new project, you will first need to add all the packages that will be required for Code Coverage and Testing.

dotnet add package Microsoft.Net.Test.Sdk
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package coverlet.msbuild

From here, you will need to add the following elements to your .csproj file.

<PropertyGroup>
...
<OutputType>Exe</OutputType>
<GenerateProgramFile>false</GenerateProgramFile>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>

These are needed in order to allow for tests to run inside the same project as your application. Since I also want to exclude *.Test.cs from my Release output, I add the following as well.

<Project ...>
<PropertyGroup>
...
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
...
<ItemGroup Condition="'$(Configuration)' != 'Release'">
<Compile Include="**/*.cs" />
</ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Release'">
<Compile Include="**/*.cs" Exclude="**/*.Test.cs" />
</ItemGroup>
</Project>

After all of this, my .csproj file may look like the following…

I can now run a test with the commands below. I’m using bash, but for windows, you can substitute the -p with /p but the hyphen variant should also work. The keys here are ExcludeByFile which will exclude your test files from testing and coverage; as well as the IncludeTestAssembly which will test your code that lives side-by-side with your tests. The other options are standard options for coverlet.

rm -rf obj bin dist coverage.*dotnet test \
-p:ExcludeByFile="**/*.Test.cs" \
-p:IncludeTestAssembly=true \
-p:CollectCoverage=true \
-p:CoverletOutputFormat=cobertura

I’m using the Code Coverage Highligher extension for VS Code, which will highlight the covered lines from the coverage.cobertura.xmlfile

Finally you can do a release build with the command below, which will exclude *.Test.cs files from the output. I find that if I don’t clear out prior build artifacts first, I will have errors when trying to do a release build after running tests.

rm -rf obj bin dist coverage.*dotnet build -c Release -o ./dist/

And there you have it, a project with side-by-side unit tests and a build output that doesn’t include those tests.

--

--

Michael J. Ryan

Food nerd (keto, omad, carnivore) — Programmer and JavaScript junkie! (node.js, mongodb, browser)