Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9703

Windowsじゃなくても.NET Coreのテストカバレッジを出力したい

$
0
0

.NET Core3.1 で開発を進めていたのですが、テストのカバレッジを求められて少し困ったので。
普段は mac 使ってます。

環境準備

プロジェクト初期化

.NET Core3.1 の SDK を利用してテストプロジェクトを作成しておきます。

$ dotnet new classlib  -f netcoreapp3.1 -o Example
$ dotnet new xunit -o Example.Tests
PacakgeVersionnuget
Microsoft.NET.Test.Sdk16.5.0https://www.nuget.org/packages/Microsoft.NET.Test.Sdk/16.5.0
coverlet.collector1.2.0https://www.nuget.org/packages/coverlet.collector/
ReportGenerator4.5.0https://www.nuget.org/packages/ReportGenerator/
xunit2.4.0https://www.nuget.org/packages/xunit/2.4.0
xunit.runner.visualstudio2.4.0https://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/

出力はこんな感じです。

Coverage.png

詳細はこんな感じです。

CoverageNumber.png

GitHub にコードがあります。Docker で動くようにしているので簡単に確認できます。気が向いたら見てください 😃

https://github.com/shikazuki/dotnet-core-test-coverage-example


Viewing all articles
Browse latest Browse all 9703

Trending Articles