LoginSignup
6
5

More than 5 years have passed since last update.

.NET Core で Code Coverage を利用する

Posted at

はじめに

.NET Core で Code Coverage を利用する方法です。テストフレームワークは xUnit.net を使います。

検証した環境は以下の通り。(カバレッジは Enterprise じゃないと使えないはず)
Visual Studio Enterprise 2017 (15.4.0)
.NET Core 2.0

プロジェクトの作成

クラスライブラリを作成します。

image.png

同じソリューションにテストプロジェクトも作成します。

image.png

テストプロジェクトにはクラスライブラリへの参照を追加しておきます。

image.png

NuGet Package の追加とアップデート

パッケージマネージャーコンソールを開いて、以下のコマンドを実行します。

Update-Package

Install-Package Microsoft.CodeCoverage -ProjectName UnitTests

テストプロジェクトは以下のようになります。

UnitTests.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeCoverage" Version="1.0.3" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
    <PackageReference Include="xunit" Version="2.3.1" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\ApplicationCore\ApplicationCore.csproj" />
  </ItemGroup>

</Project>

テストメソッドの追加

クラスライブラリにテスト対象のメソッドを追加します。

Class1.cs
using System;

namespace ApplicationCore
{
    public class Class1
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}

テストプロジェクトにテストメソッドを追加します。

UnitTest1.cs
using System;
using Xunit;
using ApplicationCore;

namespace UnitTests
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var sut = new Class1();

            Assert.Equal(5, sut.Add(2, 3));
        }
    }
}

DebugType の変更

クラスライブラリの DebugType を Full にします。現時点では Full でないとカバレッジが利用できません。

ApplicationCore.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <DebugType>Full</DebugType>
  </PropertyGroup>

</Project>

Working with code coverage
temporary workaround と書いてあるので、そのうち不要になるのかも。

分析の実行

[テスト] - [コードカバレッジの分析] - [すべてのテスト] を実行します。テストが実行され、コードカバレッジの結果が表示されます。

image.png

コマンドラインからの実行

コマンドラインから実行する場合は、テストプロジェクトのアセンブリを指定して実行します。結果はカレントディレクトリの TestResults フォルダ 配下に出力されます。出力された .coverage ファイルは Visual Studio に読み込ませて確認できます。

vstest.console.exe  --collect:"Code Coverage" --framework:".NETCoreApp,Version=v2.0" "C:\Source\CoverageSample\UnitTests\bin\Debug\netcoreapp2.0\UnitTests.dll"

まとめ

Visual Studio Enterprise は高いんですよねぇ。。。カバレッジぐらいは Professional とか Community でも使えるようにしてほしい。

6
5
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
6
5