How to Use OpenCover and ReportGenerator for Unit Test Coverage in VS.NET 2012 (Free Tools for Beginners)
Unit testing is a cornerstone of reliable software development, ensuring your code works as intended. But how do you know how much of your code is actually tested? That’s where test coverage tools come in. They measure the percentage of code executed during testing, helping you identify untested or under-tested areas.
While paid tools like ReSharper or dotCover offer robust coverage features, they can be costly for beginners or small projects. Fortunately, OpenCover (a free, open-source code coverage tool) and ReportGenerator (a free report generator) provide a powerful, budget-friendly alternative—even for older IDEs like Visual Studio .NET 2012.
This guide will walk you through installing these tools, writing unit tests, collecting coverage data, and generating easy-to-understand reports. By the end, you’ll be able to measure and improve your test coverage like a pro—no expensive licenses required!
Table of Contents#
- Prerequisites
- Installing OpenCover
- Installing ReportGenerator
- Writing Unit Tests in VS.NET 2012
- Running OpenCover to Collect Coverage Data
- Generating Reports with ReportGenerator
- Analyzing the Coverage Report
- Troubleshooting Common Issues
- Conclusion
- References
Prerequisites#
Before getting started, ensure you have the following:
- Visual Studio .NET 2012 (any edition: Professional, Premium, or Ultimate; Express editions may lack some unit testing features).
- .NET Framework 4.5 or earlier (VS2012 supports up to .NET 4.5).
- NuGet Package Manager (pre-installed in VS2012; verify via
Tools > Library Package Manager > Package Manager Console). - Basic understanding of C# and unit testing (we’ll use MSTest, integrated with VS2012).
Installing OpenCover#
OpenCover is a command-line tool that instruments your code, runs your unit tests, and collects coverage data in an XML format. Here’s how to install it:
Step 1: Open the Package Manager Console#
In VS2012, go to Tools > Library Package Manager > Package Manager Console.
Step 2: Install OpenCover via NuGet#
Run the following command in the console:
Install-Package OpenCover NuGet will download and install OpenCover into your project’s packages folder (e.g., [Solution Directory]\packages\OpenCover.<version>\tools).
What OpenCover Does#
- Instruments your compiled code to track which lines/branches are executed.
- Runs your unit tests (via a test runner like MSTest).
- Collects coverage data and saves it to an XML file (e.g.,
coverage.xml).
Installing ReportGenerator#
OpenCover’s XML output is not human-readable. ReportGenerator converts this XML into interactive HTML reports, making it easy to analyze coverage.
Step 1: Install ReportGenerator via NuGet#
In the Package Manager Console, run:
Install-Package ReportGenerator ReportGenerator will install to [Solution Directory]\packages\ReportGenerator.<version>\tools.
What ReportGenerator Does#
- Takes OpenCover’s XML output as input.
- Generates reports in formats like HTML, XML, or CSV (HTML is most user-friendly).
- Highlights covered/uncovered lines, methods, and classes with color-coding.
Writing Unit Tests in VS.NET 2012#
To demonstrate coverage, let’s create a simple project and unit tests.
Step 1: Create a Class Library#
- In VS2012, go to
File > New > Project. - Select
Visual C# > Class Library, name itMathUtils, and click OK.
Step 2: Add a Sample Class#
Replace the default Class1.cs with:
namespace MathUtils
{
public class Calculator
{
// Adds two integers
public int Add(int a, int b)
{
if (a < 0 || b < 0)
throw new ArgumentException("Numbers must be non-negative.");
return a + b;
}
// Multiplies two integers (we’ll leave this untested initially!)
public int Multiply(int a, int b)
{
return a * b;
}
}
} Step 3: Create a Unit Test Project#
- Right-click the solution >
Add > New Project. - Select
Visual C# > Test > Unit Test Project, name itMathUtils.Tests, and click OK.
Step 4: Write Unit Tests#
Replace UnitTest1.cs with:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MathUtils;
namespace MathUtils.Tests
{
[TestClass]
public class CalculatorTests
{
[TestMethod]
public void Add_PositiveNumbers_ReturnsSum()
{
// Arrange
var calculator = new Calculator();
// Act
var result = calculator.Add(2, 3);
// Assert
Assert.AreEqual(5, result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Add_NegativeNumber_ThrowsException()
{
var calculator = new Calculator();
calculator.Add(-1, 2); // Should throw
}
}
} Step 5: Verify Tests Pass#
- Build the solution (
Build > Build Solution). - Open Test Explorer (
Test > Windows > Test Explorer). - Click Run All; both tests should pass (green checkmarks).
Running OpenCover to Collect Coverage Data#
Now, use OpenCover to run your tests and collect coverage data.
Step 1: Locate OpenCover.Console.exe#
OpenCover’s main executable is OpenCover.Console.exe, located in:
[Solution Directory]\packages\OpenCover.<version>\tools
Step 2: Open a Command Prompt#
- Navigate to your solution directory (e.g.,
cd C:\Projects\MathUtilsSolution).
Step 3: Run OpenCover with MSTest#
OpenCover needs to:
- Target the MSTest runner (
MSTest.exe, integrated with VS2012). - Specify your test assembly.
- Output coverage data to an XML file.
Use this command (replace placeholders with your paths):
packages\OpenCover.<version>\tools\OpenCover.Console.exe ^
-target:"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\MSTest.exe" ^
-targetargs:"/testcontainer:MathUtils.Tests\bin\Debug\MathUtils.Tests.dll" ^
-output:coverage.xml ^
-filter:"+[MathUtils*]* -[MathUtils.Tests*]*" ^
-register:user Breakdown of Parameters:#
-target: Path to the test runner (MSTest.exe). VS2012 installs it here by default.-targetargs: Arguments for MSTest: path to your test DLL (MathUtils.Tests.dll).-output: Path to save the XML coverage data (coverage.xml).-filter:+[MathUtils*]*: Include all types/methods in assemblies starting withMathUtils(your main project).-[MathUtils.Tests*]*: Exclude test assemblies (we don’t need coverage for tests).
-register:user: Registers OpenCover’s profiler (required for code instrumentation).
Step 4: Run the Command#
If successful, you’ll see output like:
Committing...
Visited Classes: 1 of 1 (100.00%)
Visited Methods: 2 of 3 (66.67%)
Visited Points: 5 of 7 (71.43%)
Visited Branches: 2 of 4 (50.00%)
A coverage.xml file will appear in your solution directory.
Generating Reports with ReportGenerator#
Now, convert coverage.xml into a readable HTML report using ReportGenerator.
Step 1: Locate ReportGenerator.exe#
ReportGenerator’s executable is in:
[Solution Directory]\packages\ReportGenerator.<version>\tools
Step 2: Run ReportGenerator#
In the command prompt, run:
packages\ReportGenerator.<version>\tools\ReportGenerator.exe ^
-reports:coverage.xml ^
-targetdir:coverageReport Parameters:#
-reports: Path to OpenCover’s XML output (coverage.xml).-targetdir: Directory to save the HTML report (coverageReport).
Step 3: Verify the Report#
A new folder coverageReport will appear. Open coverageReport\index.htm in your browser to view the report.
Analyzing the Coverage Report#
The HTML report provides a detailed breakdown of coverage. Let’s explore key sections:
1. Summary Dashboard#
At the top, you’ll see overall coverage metrics:
- Assembly Coverage:
MathUtils(our main project) shows ~66% method coverage (we wrote tests forAddbut notMultiply). - Class Coverage:
Calculatorhas 2/3 methods covered.
2. Detailed Method Breakdown#
Click MathUtils > Calculator to see line-by-line coverage:
- Green lines: Covered (e.g.,
Add’s valid and exception-throwing paths). - Red lines: Not covered (e.g.,
Multiplymethod—we forgot to test it!).
3. Fixing Gaps#
To improve coverage:
- Add a test for
MultiplyinCalculatorTests:[TestMethod] public void Multiply_PositiveNumbers_ReturnsProduct() { var calculator = new Calculator(); Assert.AreEqual(6, calculator.Multiply(2, 3)); } - Re-run OpenCover and ReportGenerator. The new report will show 100% method coverage for
Calculator.
Troubleshooting Common Issues#
Issue: "No results, this could be for a number of reasons"#
- Cause: OpenCover didn’t find your tests or excluded all code via filters.
- Fix:
- Verify the
-targetargspath toMathUtils.Tests.dllis correct. - Check the
-filter: Ensure+[MathUtils*]*includes your main assembly (no typos in the assembly name).
- Verify the
Issue: MSTest.exe not found#
- Cause: Incorrect path to
MSTest.exe. - Fix: Verify VS2012 is installed to
C:\Program Files (x86)\Microsoft Visual Studio 11.0\(default path).
Issue: Access Denied#
- Cause: OpenCover needs permission to instrument code.
- Fix: Run the command prompt as Administrator.
Conclusion#
OpenCover and ReportGenerator are powerful, free tools that make unit test coverage accessible even for beginners using VS.NET 2012. By following this guide, you can:
- Install tools via NuGet.
- Collect coverage data with OpenCover.
- Generate interactive HTML reports with ReportGenerator.
- Identify and fix untested code.
With these tools, you’ll write more reliable software by ensuring your tests cover critical code paths—no expensive licenses required!
References#
- OpenCover GitHub (official documentation).
- ReportGenerator GitHub (report generation guide).
- MSTest Command-Line Options (VS2012) (MSTest.exe parameters).
- NuGet Gallery: OpenCover
- NuGet Gallery: ReportGenerator