🐳

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

2024/12/31に公開

.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

ソース

namespace Example
{
    public class Number
    {
        public static bool IsEven(int num)
        {
            if (num % 2 == 0)
            {
                return true;
            }
            return false;
        }
    }
}
using System;
using Xunit;
using Example;
namespace Example.Tests
{
    public class NumberTest
    {
        [Fact]
        public void IsEven_ValuesEqual2_ReturnTrue()
        {
            var actual = Number.IsEven(2);
            Assert.True(actual);
        }
        [Fact]
        public void IsEven_ValuesEqual3_ReturnFalse()
        {
            var actual = 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

Discussion