mcpField
D
dotnet-add-testing

dotnet-add-testing

github.com/wshaddixテスト・品質8679 回インストール35 週間前に更新
リポジトリ

dotnet-add-testing について

既存の.NETプロジェクトにテスト基盤を追加するスキルです。xUnitテストプロジェクト、coverletのカバレッジ設定、標準的なディレクトリ構成を用意し、詳細なテスト手法は関連スキルに委ねます。

主な機能

  1. 01xUnitテストプロジェクトの作成
  2. 02coverletによるコードカバレッジ設定
  3. 03テスト用ビルドプロパティの設定
  4. 04CPMへのテストパッケージ登録
  5. 05初期テストと命名規則の追加

活用シーン

  1. 01既存ソリューションへの単体テスト基盤の追加
  2. 02dotnet testでのカバレッジ収集設定
  3. 03統合テスト用プロジェクト構成の作成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-add-testing

インストール後、Claude Code で/dotnet-add-testingを入力して読み込まれたか確認します。

詳細

dotnet-add-testing

既存の .NET プロジェクトにテストインフラストラクチャのスキャフォールディングを追加します。xUnit を使用したテストプロジェクトを作成し、coverlet によるコードカバレッジを設定して、慣例的なディレクトリ構造を整えます。

対象範囲: このスキルで提供するのはテストプロジェクトのスキャフォールディングのみです。xUnit v3 の機能、WebApplicationFactory を使用した統合テスト、UI テスト、スナップショットテスト、テスト品質メトリクス、テスト戦略のガイダンスなど、詳細なテストパターンについては、[skill:dotnet-testing-strategy] と関連するテストスキルを参照してください。

前提条件: 最初に [skill:dotnet-version-detection] を実行して SDK バージョンと TFM を確認してください。[skill:dotnet-project-analysis] を実行して、既存のソリューション構造を把握してください。

相互参照:ソリューション全体のレイアウト規約については [skill:dotnet-project-structure]、新規プロジェクトにテストのスキャフォールディングを含める場合は [skill:dotnet-scaffold-project]、テスト固有のアナライザー抑制については [skill:dotnet-add-analyzers] を参照してください。


テストプロジェクトの構造

src/ のプロジェクト名を tests/ の下にそのまま反映する慣例に従います。

MyApp/
├── src/
│   ├── MyApp.Core/
│   ├── MyApp.Api/
│   └── MyApp.Infrastructure/
└── tests/
    ├── MyApp.Core.UnitTests/
    ├── MyApp.Api.UnitTests/
    ├── MyApp.Api.IntegrationTests/
    └── Directory.Build.props          # Test-specific build settings

命名規則:

  • *.UnitTests -- 外部依存関係のない独立したテスト
  • *.IntegrationTests -- 実際のインフラストラクチャ(データベース、HTTP、ファイルシステム)を使用するテスト
  • *.FunctionalTests -- アプリケーションスタック全体を通したエンドツーエンドテスト

ステップ 1:テストプロジェクトを作成する

# Create xUnit test project
dotnet new xunit -n MyApp.Core.UnitTests -o tests/MyApp.Core.UnitTests

# Add to solution
dotnet sln add tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj

# Add reference to the project under test
dotnet add tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj \
  reference src/MyApp.Core/MyApp.Core.csproj
生成されたプロジェクトを整理する

Directory.Build.props ですでに定義されているプロパティを削除します。


<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" />
    <PackageReference Include="xunit.v3" />
    <PackageReference Include="xunit.runner.visualstudio" />
    <PackageReference Include="coverlet.collector" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\src\MyApp.Core\MyApp.Core.csproj" />
  </ItemGroup>
</Project>

CPM を使用する場合、Version 属性は Directory.Packages.props で管理します。生成された .csproj から削除してください。


ステップ 2:テスト固有のビルドプロパティを追加する

すべてのテストプロジェクトの設定をカスタマイズするため、tests/Directory.Build.props を作成します。


<Project>
  <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
  <PropertyGroup>
    <IsPackable>false</IsPackable>
    <IsTestProject>true</IsTestProject>
    
    <UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
    
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
  </PropertyGroup>
</Project>

このファイルはルートの Directory.Build.props(Nullable、ImplicitUsings、LangVersion などの共有設定用)をインポートし、テスト固有のプロパティを上書きします。


ステップ 3:CPM にテストパッケージを登録する

Directory.Packages.props にテストパッケージのバージョンを追加します。


<ItemGroup>
  
  <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
  <PackageVersion Include="xunit.v3" Version="3.2.2" />
  <PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
  <PackageVersion Include="coverlet.collector" Version="8.0.0" />
</ItemGroup>
任意:モックライブラリ

テストダブルが必要な場合は、モックライブラリを追加します。

<PackageVersion Include="NSubstitute" Version="5.3.0" />

または、アサーションライブラリの場合:

<PackageVersion Include="FluentAssertions" Version="8.0.1" />

ステップ 4:コードカバレッジを設定する

Coverlet(Collector モード)

coverlet.collector パッケージは、データコレクターを介して dotnet test と統合されます。基本的なカバレッジ測定に追加の設定は不要です。

カバレッジレポートを生成します。

# Collect coverage (Cobertura format by default)
dotnet test --collect:"XPlat Code Coverage"

# Results appear in TestResults/*/coverage.cobertura.xml
カバレッジのしきい値

CI でしきい値を適用するには、しきい値チェックに coverlet.msbuild を使用します。


<PackageReference Include="coverlet.msbuild" />
# Enforce minimum coverage threshold
dotnet test /p:CollectCoverage=true \
  /p:CoverageOutputFormat=cobertura \
  /p:Threshold=80 \
  /p:ThresholdType=line
カバレッジレポートの生成

人が読みやすい HTML レポートには reportgenerator を使用します。

# Install globally
dotnet tool install -g dotnet-reportgenerator-globaltool

# Generate HTML report
reportgenerator \
  -reports:"tests/**/coverage.cobertura.xml" \
  -targetdir:coverage-report \
  -reporttypes:Html

ステップ 5:テスト用の EditorConfig オーバーライドを追加する

ルートの .editorconfig に、テスト固有の緩和設定を追加します。

[tests/**.cs]
# Allow underscores in test method names (Given_When_Then or Should_Behavior)
dotnet_diagnostic.CA1707.severity = none

# Test parameters are validated by the framework
dotnet_diagnostic.CA1062.severity = none

# ConfigureAwait not relevant in test context
dotnet_diagnostic.CA2007.severity = none

# Tests often have intentionally unused variables for assertions
dotnet_diagnostic.IDE0059.severity = suggestion

ステップ 6:スターターテストを作成する

テンプレートで生成された UnitTest1.cs を、適切に構成されたテストに置き換えます。

namespace MyApp.Core.UnitTests;

public class SampleServiceTests
{
    [Fact]
    public void Method_Condition_ExpectedResult()
    {
        // Arrange
        var sut = new SampleService();

        // Act
        var result = sut.DoWork();

        // Assert
        Assert.NotNull(result);
    }

    [Theory]
    [InlineData(1, 2, 3)]
    [InlineData(0, 0, 0)]
    [InlineData(-1, 1, 0)]
    public void Add_TwoNumbers_ReturnsSum(int a, int b, int expected)
    {
        var result = Calculator.Add(a, b);
        Assert.Equal(expected, result);
    }
}
テストの命名規則

Method_Condition_ExpectedResult のパターンを使用します。

  • CreateUser_WithValidInput_ReturnsUser
  • GetById_WhenNotFound_ReturnsNull
  • Delete_WithoutPermission_ThrowsUnauthorized

検証

テストインフラストラクチャを追加したら、すべてが動作することを確認します。

# Restore (regenerate lock files if using CPM)
dotnet restore

# Build (verifies project references and analyzer config)
dotnet build --no-restore

# Run tests
dotnet test --no-build

# Run with coverage
dotnet test --collect:"XPlat Code Coverage"

統合テストプロジェクトを追加する

WebApplicationFactory やデータベースアクセスが必要な統合テストの場合:

dotnet new xunit -n MyApp.Api.IntegrationTests -o tests/MyApp.Api.IntegrationTests
dotnet sln add tests/MyApp.Api.IntegrationTests/MyApp.Api.IntegrationTests.csproj
dotnet add tests/MyApp.Api.IntegrationTests/MyApp.Api.IntegrationTests.csproj \
  reference src/MyApp.Api/MyApp.Api.csproj

統合テスト用パッケージを CPM に追加します(Microsoft.AspNetCore.Mvc.Testing のメジャーバージョンはターゲットフレームワークに合わせてください。例:net8.0 には 8.x、net9.0 には 9.x、net10.0 には 10.x)。


<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
<PackageVersion Include="Testcontainers" Version="4.3.0" />

統合テストの詳細(WebApplicationFactory のパターン、テストコンテナー、データベースフィクスチャ)については、[skill:dotnet-integration-testing] を参照してください。


次のステップ

このスキルでは、テストプロジェクトのひな形作成を扱います。テストについてさらに詳しく知りたい場合は、以下を参照してください。

  • xUnit v3 の機能とパターン -- [skill:dotnet-xunit]
  • WebApplicationFactory を使った統合テスト -- [skill:dotnet-integration-testing]
  • UI テスト(Blazor、MAUI、Uno) -- [skill:dotnet-blazor-testing]、[skill:dotnet-maui-testing]、[skill:dotnet-uno-testing]
  • スナップショットテスト -- [skill:dotnet-snapshot-testing]
  • テスト品質とカバレッジの適用 -- [skill:dotnet-test-quality]
  • CI テストレポート -- 入門編は [skill:dotnet-add-ci]、応用編は [skill:dotnet-gha-build-test] と [skill:dotnet-ado-build-test]

参考資料

コメント