Adding Unit Tests and Code Coverage to .NET Core Applications with xUnit, Coverlet, and Azure DevOps
This article demonstrates how to create unit tests for .NET Core methods using xUnit, measure code coverage with Coverlet, generate readable reports with ReportGenerator, and automate testing and coverage analysis in Azure DevOps pipelines, while also showing how to display project badges.
The article begins by explaining why unit testing is essential for .NET Core projects and introduces a simple method public int SimpleMethod(int a1, int a2) { return a1 + a2; } as a baseline example.
It then presents a more complex utility method public Type[] MyDemoMethod(Type type, Type genericType) { return type.GetInterfaces().Where(i => IsGenericType(i)).SelectMany(i => i.GetGenericArguments()).ToArray(); bool IsGenericType(Type type1) => type1.IsGenericType && type1.GetGenericTypeDefinition() == genericType; } to illustrate testing of methods with branching logic.
Using the xUnit framework, the article shows how to write test cases for a method public int CalDemo(int s, bool checkSign = true) { if (s > 10 && checkSign) { return s << 2; } else { return s; } } with two facts: one asserting the result 44 when the input is 11, and another asserting 9 when the input is 9.
After running the tests in Visual Studio’s Test Explorer, the guide moves to code‑coverage measurement. It recommends installing the coverlet.collector NuGet package ( dotnet add package coverlet.collector ) and executing tests with coverage collection via dotnet test --collect:"XPlat Code Coverage" .
The generated Cobertura XML report is then transformed into a human‑readable HTML report using ReportGenerator ( dotnet tool install --global dotnet-reportgenerator-globaltool and reportgenerator "-reports:**\coverage.cobertura.xml" "-targetdir:coveragereport" ).
To automate the whole process, the article outlines an Azure DevOps pipeline that restores the project, runs dotnet test with Coverlet, and publishes the coverage report, showing screenshots of pipeline configuration and results.
Finally, it explains how to expose the coverage and build status as badges using Azure Pipelines and shields.io, and provides tips for testing internal classes, handling dependency injection, and scaling tests across multiple projects.
YunZhu Net Technology Team
Technical practice sharing from the YunZhu Net Technology Team
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.