次の方法で共有


MSTest で組織とメタデータをテストする

MSTest には、テストの整理、メタデータの追加、テストの作業追跡システムへのリンクのための属性が用意されています。 これらの属性は、大規模なテスト スイートでテストを効果的にフィルター処理、並べ替え、管理するのに役立ちます。

概要

メタデータ属性は、テスト メソッドの Visual Studio の [プロパティ ] ウィンドウに表示されます。 彼らはあなたを助ける:

  • テストを整理する: カテゴリ、優先度、所有者別にテストをグループ化します。
  • テスト実行のフィルター処理: メタデータに基づいてテストの特定のサブセットを実行します。
  • テスト カバレッジの追跡: テストを作業項目や要件に関連付ける。
  • レポートの生成: テスト レポートとダッシュボードにメタデータを含めます。

テストの分類

TestCategoryAttribute

TestCategoryAttributeは、フィルター処理と編成のカテゴリにテストをグループ化します。 この属性はメソッド、クラス、またはアセンブリ レベルで適用でき、複数のレベルで適用するとカテゴリが結合されます。

メソッド レベルのカテゴリ

カテゴリを直接テスト メソッドに適用して、きめ細かい制御を行います。

[TestClass]
public class OrderTests
{
    [TestMethod]
    [TestCategory("Integration")]
    public void CreateOrder_SavesOrderToDatabase()
    {
        // Integration test
    }

    [TestMethod]
    [TestCategory("Unit")]
    public void CalculateTotal_ReturnsSumOfItems()
    {
        // Unit test
    }

    [TestMethod]
    [TestCategory("Integration")]
    [TestCategory("Slow")]
    public void ProcessLargeOrder_CompletesSuccessfully()
    {
        // Multiple categories allowed
    }
}

クラス レベルのカテゴリ

テスト クラスにカテゴリを適用して、そのクラス内のすべてのテスト メソッドにそのカテゴリを割り当てます。

[TestClass]
[TestCategory("Payments")]
public class PaymentServiceTests
{
    [TestMethod]
    public void ProcessPayment_ValidCard_Succeeds()
    {
        // Inherits "Payments" category from class
    }

    [TestMethod]
    [TestCategory("Slow")]
    public void ProcessBatchPayments_LargeVolume_CompletesSuccessfully()
    {
        // Has both "Payments" (from class) and "Slow" (from method) categories
    }
}

アセンブリ レベルのカテゴリ

アセンブリ レベルでカテゴリを適用して、テスト アセンブリ全体のすべてのテストを分類します。 この方法は、プロジェクト間でテストの種類を区別する場合に役立ちます。

// In AssemblyInfo.cs or any file in your test project
using Microsoft.VisualStudio.TestTools.UnitTesting;

[assembly: TestCategory("E2E")]

アセンブリ レベルのカテゴリを使用して、テスト プロジェクトをテストの種類別に整理します。

プロジェクト アセンブリ カテゴリ 目的
MyApp.UnitTests Unit 高速で分離された単体テスト
MyApp.IntegrationTests Integration 外部依存関係を持つテスト
MyApp.E2ETests E2E エンド ツー エンドのシナリオ テスト

カテゴリ別にテストをフィルター処理する

dotnet test コマンドを使用して、カテゴリ別にテストを実行します。

# Run only integration tests
dotnet test --filter TestCategory=Integration

# Run tests in multiple categories
dotnet test --filter "TestCategory=Integration|TestCategory=Unit"

# Exclude slow tests
dotnet test --filter TestCategory!=Slow

Visual Studio テスト エクスプローラーで、 Trait: プレフィックス付きの検索ボックスを使用します。

  • Trait:"TestCategory=Integration" - 統合テストを示します
  • -Trait:"TestCategory=Slow" - 低速テストを除外

TestPropertyAttribute

TestPropertyAttributeは、カスタムのキーと値のメタデータをテストに追加します。 組み込みの属性がニーズを満たしていない場合は、この属性を使用します。

[TestClass]
public class CustomMetadataTests
{
    [TestMethod]
    [TestProperty("Feature", "Authentication")]
    [TestProperty("Sprint", "23")]
    [TestProperty("RiskLevel", "High")]
    public void Login_WithValidCredentials_Succeeds()
    {
        // Test with custom properties
    }

    [TestMethod]
    [TestProperty("Feature", "Authorization")]
    [TestProperty("RequirementId", "REQ-AUTH-001")]
    public void AccessAdminPage_RequiresAdminRole()
    {
        // Link to requirements
    }
}

プロパティは、Visual Studio の [プロパティ] ウィンドウの [ テスト固有] の下に表示されます。

カスタム プロパティでフィルター処理する

# Filter by custom property
dotnet test --filter "Feature=Authentication"

所有権と優先度をテストする

OwnerAttribute

OwnerAttributeは、テストの責任者を識別します。

[TestClass]
public class PaymentTests
{
    [TestMethod]
    [Owner("jsmith")]
    public void ProcessPayment_ChargesCorrectAmount()
    {
        // John Smith owns this test
    }

    [TestMethod]
    [Owner("team-payments")]
    public void RefundPayment_CreditsCustomerAccount()
    {
        // Team responsibility
    }
}

所有者でテストをフィルター:

dotnet test --filter Owner=jsmith

PriorityAttribute

PriorityAttributeは、相対的なテストの重要度を示します。 値が小さいと、優先度が高いことを示します。

[TestClass]
public class CriticalPathTests
{
    [TestMethod]
    [Priority(0)]
    public void Login_IsAlwaysAvailable()
    {
        // Highest priority - core functionality
    }

    [TestMethod]
    [Priority(1)]
    public void CreateAccount_WorksCorrectly()
    {
        // High priority
    }

    [TestMethod]
    [Priority(2)]
    public void CustomizeProfile_SavesPreferences()
    {
        // Medium priority
    }
}

優先順位でテストをフィルター処理する:

# Run only highest priority tests
dotnet test --filter Priority=0

# Run high priority or higher
dotnet test --filter "Priority=0|Priority=1"

DescriptionAttribute

DescriptionAttributeは、テストで検証される内容について人間が判読できる説明を提供します。

Warnung

Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute ではなく、System.ComponentModel.DescriptionAttribute を使用してください。 MSTEST0031 アナライザーは、不適切な使用状況を検出します。

[TestClass]
public class DocumentedTests
{
    [TestMethod]
    [Description("Verifies that orders over $100 receive a 10% discount")]
    public void ApplyDiscount_LargeOrder_Gets10PercentOff()
    {
        // Test implementation
    }

    [TestMethod]
    [Description("Ensures email validation rejects malformed addresses")]
    public void ValidateEmail_InvalidFormat_ReturnsFalse()
    {
        // Test implementation
    }
}

作業項目のトラッキング

WorkItemAttribute

WorkItemAttributeは、テストを追跡システム (Azure DevOps など) の作業項目にリンクします。

[TestClass]
public class BugFixTests
{
    [TestMethod]
    [WorkItem(12345)]
    [Description("Regression test for bug #12345")]
    public void DatePicker_LeapYear_HandlesFebruary29()
    {
        // Test that verifies the bug fix
    }

    [TestMethod]
    [WorkItem(67890)]
    [WorkItem(67891)]  // Can link multiple work items
    public void Export_LargeDataset_CompletesWithinTimeout()
    {
        // Test related to multiple work items
    }
}

GitHubWorkItemAttribute

GitHubWorkItemAttributeは、テストを GitHub の問題にリンクします。

[TestClass]
public class GitHubLinkedTests
{
    [TestMethod]
    [GitHubWorkItem("https://github.com/myorg/myrepo/issues/42")]
    public void FeatureX_WorksAsExpected()
    {
        // Test linked to GitHub issue #42
    }

    [TestMethod]
    [GitHubWorkItem("https://github.com/myorg/myrepo/issues/100")]
    [Ignore("Waiting for upstream fix")]
    public void DependentFeature_RequiresUpdate()
    {
        // Ignored test linked to tracking issue
    }
}

作業項目の属性は、 Ignoreと組み合わせる場合に特に重要です。

[TestMethod]
[Ignore("Known issue, tracked in work item")]
[WorkItem(99999)]
public void KnownIssue_AwaitingFix()
{
    // Provides traceability for why the test is ignored
}

属性の組み合わせ

包括的なテスト組織のために複数のメタデータ属性を結合します。

[TestClass]
public class FullyDocumentedTests
{
    [TestMethod]
    [TestCategory("Integration")]
    [TestCategory("API")]
    [Owner("payment-team")]
    [Priority(1)]
    [Description("Verifies that the payment API returns correct error codes for invalid requests")]
    [WorkItem(54321)]
    [TestProperty("Sprint", "24")]
    [TestProperty("Feature", "ErrorHandling")]
    public void PaymentAPI_InvalidRequest_ReturnsAppropriateErrorCode()
    {
        // Well-documented test with full traceability
    }
}

ベスト プラクティス

  1. 一貫性のあるカテゴリを使用する: プロジェクト全体のテスト カテゴリの名前付け規則を確立します。

  2. 優先順位を戦略的に設定する: 実行可能なビルドに合格する必要があるクリティカル パス テスト用に Priority(0) を予約します。

  3. 作業項目へのリンク: 追跡可能性のために、テストを関連する作業項目 (特にバグ回帰テスト) に常にリンクします。

  4. ドキュメント テストの目的: メソッド名が意図を完全に説明していない複雑なテストには、 Description を使用します。

  5. メタデータを最新の状態に保つ: テスト スコープまたは所有権の変更時にメタデータを更新します。

  6. フィルター処理にカテゴリを使用する: CI/CD パイプラインのニーズをサポートするカテゴリを設計します (例: "Smoke"、"Nightly"、"Integration")。

テストのフィルタリングプロセス

コマンドライン フィルタリング

# Filter by category
dotnet test --filter TestCategory=Unit

# Filter by owner
dotnet test --filter Owner=jsmith

# Filter by priority
dotnet test --filter Priority=0

# Combine filters (AND)
dotnet test --filter "TestCategory=Integration&Priority=0"

# Combine filters (OR)
dotnet test --filter "TestCategory=Smoke|TestCategory=Critical"

# Exclude by filter
dotnet test --filter TestCategory!=Slow

# Filter by custom property
dotnet test --filter "Feature=Payments"

Visual Studio テスト エクスプローラー

テスト エクスプローラーで検索ボックスを使用します。

  • Trait:"TestCategory=Integration" - カテゴリでフィルターする
  • Trait:"Owner=jsmith" - 所有者でフィルター
  • Trait:"Priority=0" - 優先度でフィルター処理する

テスト フィルター処理の詳細については、「 選択的単体テストの実行」を参照してください。

こちらも参照ください