Yoro
Yoro

Reputation: 1740

How to get .NET code coverage analysis in VS Code?

I wrote NUnit tests to test .NET code. Now I want to see my coverage statistics in VS Code.

Is there any way to get visual/textual coverage analysis for .NET unit tests in VS Code?

Maybe there is some good extension for that?

Upvotes: 3

Views: 7244

Answers (2)

G-DE
G-DE

Reputation: 41

To update this for anyone else looking, C# Dev Kit looks to add Code Coverage along with many other features.

F1 -> Test: Run All Tests with Coverage

This then displays in the file explorer, or in the "Test Coverage" panel of the "Testing" tab.

Code coverage indicator displayed in the file explorer

Upvotes: 2

Yoro
Yoro

Reputation: 1740

Currently, I don't know any extensions for that in VS Code. But I found another way to see coverage stats in VS Code.

All you need to do is:

Install .NET report generator in terminal with command:

dotnet tool install -g dotnet-reportgenerator-globaltool

Add Coverlet MS build package from NuGet to testing project

dotnet add package coverlet.msbuild

Run dotnet tests from terminal with command:

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=lcov /p:CoverletOutput=lcov.info

Add configuration to tasks.json file in .vscode folder (If file doesn't exist create new one):

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Generate coverage stats",
            "command": "reportgenerator",
            "type": "shell",
            "args": [
                "-reports:${workspaceFolder}/YourUnitTestProjectFolder/lcov.info",
                "-targetdir:${workspaceFolder}/YourUnitTestProjectFolder/covstats"
            ],
            "problemMatcher": []
        }
    ]
}

Launch task in VS Code by pressing Ctrl + Shift + P and executing Tasks: Run task command. Tasks: Run task

And then press Generate coverage stats

Generate coverage stats

In your test project should appear covstats folder which contain index.html file. With right mouse button click Show preview on that file. Coverage analysis will appear.

enter image description here

Creds to: https://jasonwatmore.com/net-vs-code-xunit-setup-unit-testing-code-coverage-in-aspnet-core .

Upvotes: 8

Related Questions