.NET Core3.1 で開発を進めていたのですが、テストのカバレッジを求められて少し困ったので。
普段は mac 使ってます。
環境準備
プロジェクト初期化
.NET Core3.1 の SDK を利用してテストプロジェクトを作成しておきます。
$ dotnet new classlib -f netcoreapp3.1 -o Example
$ dotnet new xunit -o Example.Tests
| Pacakge | Version | nuget |
|---|---|---|
| Microsoft.NET.Test.Sdk | 16.5.0 | https://www.nuget.org/packages/Microsoft.NET.Test.Sdk/16.5.0 |
| coverlet.collector | 1.2.0 | https://www.nuget.org/packages/coverlet.collector/ |
| ReportGenerator | 4.5.0 | https://www.nuget.org/packages/ReportGenerator/ |
| xunit | 2.4.0 | https://www.nuget.org/packages/xunit/2.4.0 |
| xunit.runner.visualstudio | 2.4.0 | https://www.nuget.org/packages/xunit.runner.visualstudio/2.4.0 |
以下のライブラリは追加する必要があります。
$ dotnet add package coverlet.collector
$ dotnet add package Microsoft.NET.Test.Sdk -v 16.5.0
$ dotnet add package ReportGenerator
ソース
Example/Number.cs
namespaceExample{publicclassNumber{publicstaticboolIsEven(intnum){if(num%2==0){returntrue;}returnfalse;}}}Example.Tests.NumberTest.cs
usingSystem;usingXunit;usingExample;namespaceExample.Tests{publicclassNumberTest{[Fact]publicvoidIsEven_ValuesEqual2_ReturnTrue(){varactual=Number.IsEven(2);Assert.True(actual);}[Fact]publicvoidIsEven_ValuesEqual3_ReturnFalse(){varactual=Number.IsEven(3);Assert.False(actual);}}}利用方法
Coverage の出力
$ dotnet test --collect:"XPlat Code Coverage"
./TestResults/{hash}/coverage.cobertura.xmlに結果が出力されます。この結果を今回は HTML に変換します。
HTML の変換
今回はプロジェクトのパッケージとしてインストールしました。この場合は、.nugetにある ReportGenerator.dll を指定して実行することになります。
$ dotnet ~/.nuget/packages/reportgenerator/4.5.0/tools/netcoreapp3.0/ReportGenerator.dll -reports:./Example.Tests/TestResults/{hash}/coverage.cobertura.xml -targetdir:./Example.Tests/TestResults/out/
出力はこんな感じです。
詳細はこんな感じです。
GitHub にコードがあります。Docker で動くようにしているので簡単に確認できます。気が向いたら見てください 😃
https://github.com/shikazuki/dotnet-core-test-coverage-example

