LoginSignup
8
4

More than 3 years have passed since last update.

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

Posted at

.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
namespace Example
{
    public class Number
    {
        public static bool IsEven(int num)
        {
            if (num % 2 == 0)
            {
                return true;
            }
            return false;
        }
    }
}
Example.Tests.NumberTest.cs
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 で動くようにしているので簡単に確認できます。気が向いたら見てください 😃

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4