This product is not supported for your selected Datadog site. ().

互換性

サポートされているランタイムとプラットフォームの一覧については、.NET Framework の互換性 と .NET/.NET Core の互換性 を参照してください。

サポート対象テストフレームワーク:

テストフレームワークバージョン
xUnit2.2 以上
NUnit3.0 以上
MsTestV214 以上
BenchmarkDotNet0.13.2 以上

報告方法の構成

Datadog にテスト結果を報告するには、Datadog .NET ライブラリを構成する必要があります。

We support auto-instrumentation for the following CI providers:

CI ProviderAuto-Instrumentation method
GitHub ActionsDatadog Test Visibility Github Action
JenkinsUI-based configuration with Datadog Jenkins plugin
GitLabDatadog Test Visibility GitLab Script
CircleCIDatadog Test Visibility CircleCI Orb

Auto-instrumentation runs on the CI executor and does not automatically apply to tests in a separate container. Before using it for containerized tests, see Tests in Containers.

If the auto-instrumentation step configures the process that runs your tests, you can skip the rest of the setup steps below.

If you are using a cloud CI provider without access to the underlying worker nodes, such as GitHub Actions or CircleCI, configure the library to use the Agentless mode. For this, set the following environment variables:

Set these variables before starting the test process. For parallel test runners, set them on the parent process so every worker inherits them.

DD_CIVISIBILITY_AGENTLESS_ENABLED=true selects Agentless mode. DD_API_KEY provides authentication but does not enable Agentless mode.

DD_CIVISIBILITY_AGENTLESS_ENABLED=true (Required for Agentless mode)
Enables Agentless mode to send test results directly to Datadog.
Default: false
DD_API_KEY (Required for Agentless mode)
The Datadog API key used to authenticate test result uploads.
Default: (empty)

If you use a Datadog site other than US1, set the following variable:

DD_SITE (Optional for Agentless mode)
The Datadog site to upload results to.
Default: datadoghq.com

If you are running tests on an on-premises CI provider, such as Jenkins or self-managed GitLab CI, install the Datadog Agent on each worker node by following the Agent installation instructions. This is the recommended option as it allows you to automatically link test results to logs and underlying host metrics.

If you are using a Kubernetes executor, Datadog recommends using the Datadog Operator. The operator includes Datadog Admission Controller which can automatically inject the tracer library into the build pods. Note: If you use the Datadog Operator, there is no need to download and inject the tracer library since the Admission Controller can do this for you, so you can skip the corresponding step below. However, you still need to make sure that your pods set the environment variables or command-line parameters necessary to enable Test Visibility.

If you are not using Kubernetes or can’t use the Datadog Admission Controller and the CI provider is using a container-based executor, set the DD_TRACE_AGENT_URL environment variable (which defaults to http://localhost:8126) in the build container running the tracer to an endpoint that is accessible from within that container. Note: Using localhost inside the build references the container itself and not the underlying worker node or any container where the Agent might be running in.

DD_TRACE_AGENT_URL includes the protocol and port (for example, http://localhost:8126) and takes precedence over DD_AGENT_HOST and DD_TRACE_AGENT_PORT, and is the recommended configuration parameter to configure the Datadog Agent’s URL for CI Visibility.

If you still have issues connecting to the Datadog Agent, use the Agentless Mode. Note: When using this method, tests are not correlated with logs and infrastructure metrics.

.NET トレーサー CLI のインストール

以下のいずれかの方法で dd-trace コマンドをインストールまたは更新してください。

テストのインスツルメンテーション

BenchmarkDotNet については、こちらの指示に従ってください。

テストスイートのインスツルメンテーションを行うには、テストコマンドの前に dd-trace ci run を付けてください。--dd-service を使用してテスト対象のサービスまたはライブラリを設定し、--dd-env を使用してテストが実行される環境を設定できます。たとえば、以下のとおりです。

dotnet test を使用する場合:

dd-trace ci run --dd-service=my-dotnet-app -- dotnet test

VSTest.Console.exe を使用する場合:

dd-trace ci run --dd-service=my-dotnet-app -- VSTest.Console.exe {test_assembly}.dll

すべてのテストは自動的にインスツルメントされます。

Microsoft.CodeCoverage nuget パッケージとの互換性

Microsoft.CodeCoverage バージョン 17.2.0 以降、Microsoft は Windows でのみデフォルトで有効になる .NET CLR Profiling API を使用する動的インスツルメンテーション を導入しました。Datadog の自動インスツルメンテーションは .NET CLR Profiling API に依存しています。この API に許可されるサブスクライバーは 1 つのみです (たとえば dd-trace)。CodeCoverage の動的インスツルメンテーションを使用すると、自動テストインスツルメンテーションが機能しなくなります。

解決策は、動的インスツルメンテーションから 静的インスツルメンテーション に切り替えることです。.runsettings ファイルの以下の構成項目を変更してください。

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
    <DataCollectionRunSettings>
        <DataCollectors>
            <DataCollector friendlyName="Code Coverage">
              <Configuration>
                <CodeCoverage>
                  <!-- Switching to static instrumentation (dynamic instrumentation collides with dd-trace instrumentation) -->
                  <EnableStaticManagedInstrumentation>True</EnableStaticManagedInstrumentation>
                  <EnableDynamicManagedInstrumentation>False</EnableDynamicManagedInstrumentation>
                  <UseVerifiableInstrumentation>False</UseVerifiableInstrumentation>
                  <EnableStaticNativeInstrumentation>True</EnableStaticNativeInstrumentation>
                  <EnableDynamicNativeInstrumentation>False</EnableDynamicNativeInstrumentation>
                  ...
                </CodeCoverage>
              </Configuration>
            </DataCollector>
        </DataCollectors>
    </DataCollectionRunSettings>
</RunSettings>

構成設定

コマンドライン引数または環境変数を使用して、CLI のデフォルト構成を変更できます。構成設定の完全なリストについては、以下を実行してください。

dd-trace ci run --help

次のリストは、主要な構成設定のデフォルト値を示しています。

--dd-service (オプション)
テスト対象のサービスまたはライブラリの名前。
環境変数: DD_SERVICE
デフォルト: リポジトリ名
例: my-dotnet-app
--dd-env (オプション)
テストが実行されている環境の名前。
環境変数: DD_ENV
デフォルト: none
例: local、ci
--agent-url (Datadog Agent を使用する場合のみ)
トレース収集用の Datadog Agent URL。http://hostname:port の形式にします。
環境変数: DD_TRACE_AGENT_URL
デフォルト: http://localhost:8126
test_session.name (環境変数としてのみ利用可能)
unit-tests、integration-tests、smoke-tests などのテストグループを識別します。
環境変数: DD_TEST_SESSION_NAME
デフォルト: CI ジョブ名とテストコマンド、または CI ジョブ名が利用できない場合はテストコマンド。
例: unit-tests、integration-tests、smoke-tests

service および env の予約タグの詳細については、unified service tagging を参照してください。他のすべての Datadog トレーサー構成 オプションも使用できます。

テストにカスタムタグを追加する

テストにカスタムタグを追加するには、まずカスタムインスツルメンテーションを構成してください。

現在アクティブなスパンを使用して、テストにカスタムタグを追加することができます。

// inside your test
var scope = Tracer.Instance.ActiveScope; // from Datadog.Trace;
if (scope != null) {
    scope.Span.SetTag("test_owner", "my_team");
}
// test continues normally
// ...

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、.NET カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

テストへのカスタム測定値の追加

テストにカスタム測定値を追加するには、まずカスタムインスツルメンテーションを構成してください。

タグと同様に、現在アクティブなスパンを使用して、テストにカスタム測定値を追加できます。

// inside your test
var scope = Tracer.Instance.ActiveScope; // from Datadog.Trace;
if (scope != null) {
    scope.Span.SetTag("memory_allocations", 16);
}
// test continues normally
// ...

これらのタグに対してフィルターや視覚化を作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、.NET カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

コードカバレッジを報告する

コードカバレッジが利用できる場合、Datadog トレーサー (v2.31.0 以降) は、テストセッションの test.code_coverage.lines_pct タグでそれを報告します。

Coverlet を使用してコードカバレッジを計算している場合は、dd-trace を実行する際に DD_CIVISIBILITY_EXTERNAL_CODE_COVERAGE_PATH 環境変数でレポートファイルへのパスを指定します。レポートファイルは、OpenCover または Cobertura 形式であることが必要です。あるいは、DD_CIVISIBILITY_CODE_COVERAGE_ENABLED=true 環境変数を使用して、Datadog トレーサーの組み込みコードカバレッジ計算を有効にすることもできます。

注: Test Impact Analysis を使用する場合、SDK の組み込みコードカバレッジはデフォルトで有効になります。

テストセッションの [Coverage] (カバレッジ) タブで、テストカバレッジの推移を見ることができます。

除外オプションの詳細については、Code Coverage を参照してください。

BenchmarkDotNet テストのインスツルメンテーション

ベンチマークテストをインスツルメンテーションするには、以下を行う必要があります。

  1. Datadog.Trace.BenchmarkDotNet NuGet パッケージ をプロジェクトに追加します (たとえば、dotnet add package Datadog.Trace.BenchmarkDotNet を使用)。
  2. Datadog.Trace.BenchmarkDotNet 属性または DatadogDiagnoser 拡張メソッドを使用して、エクスポーターを使用するようにプロジェクトを構成します。WithDatadog()たとえば、以下のとおりです。
using BenchmarkDotNet.Attributes;
using Datadog.Trace.BenchmarkDotNet;

[DatadogDiagnoser]
[MemoryDiagnoser]
public class OperationBenchmark
{
    [Benchmark]
    public void Operation()
    {
        // ...
    }
}
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
using Datadog.Trace.BenchmarkDotNet;

var config = DefaultConfig.Instance
              .WithDatadog();

BenchmarkRunner.Run<OperationBenchmark>(config);
  1. 報告方法を構成します。
  2. 通常通りベンチマークプロジェクトを実行すると、すべてのベンチマークテストが自動的にインスツルメンテーションされます。

Datadog uses Git information for visualizing your test results and grouping them by repository, branch, and commit. Git metadata is automatically collected by the test instrumentation from CI provider environment variables and the local .git folder in the project path, if available.

If you are running tests in non-supported CI providers or with no .git folder, you can set the Git information manually using environment variables. These environment variables take precedence over any auto-detected information. Set the following environment variables to provide Git information:

DD_GIT_REPOSITORY_URL
URL of the repository where the code is stored. Both HTTP and SSH URLs are supported.
Example: git@github.com:MyCompany/MyApp.git, https://github.com/MyCompany/MyApp.git
DD_GIT_BRANCH
Git branch being tested. Leave empty if providing tag information instead.
Example: develop
DD_GIT_TAG
Git tag being tested (if applicable). Leave empty if providing branch information instead.
Example: 1.0.1
DD_GIT_COMMIT_SHA
Full commit hash.
Example: a18ebf361cc831f5535e58ec4fae04ffd98d8152
DD_GIT_COMMIT_MESSAGE
Commit message.
Example: Set release number
DD_GIT_COMMIT_AUTHOR_NAME
Commit author name.
Example: John Smith
DD_GIT_COMMIT_AUTHOR_EMAIL
Commit author email.
Example: john@example.com
DD_GIT_COMMIT_AUTHOR_DATE
Commit author date in ISO 8601 format.
Example: 2021-03-12T16:00:28Z
DD_GIT_COMMIT_COMMITTER_NAME
Commit committer name.
Example: Jane Smith
DD_GIT_COMMIT_COMMITTER_EMAIL
Commit committer email.
Example: jane@example.com
DD_GIT_COMMIT_COMMITTER_DATE
Commit committer date in ISO 8601 format.
Example: 2021-03-12T16:00:28Z

カスタムインスツルメンテーション

注: カスタムインスツルメンテーションのセットアップは、 dd-trace のバージョンに依存します。カスタムインスツルメンテーションを使用するには、 dd-trace および Datadog.Trace NuGet パッケージのパッケージバージョンが同期しているようにすることが必要です。

.NET アプリケーションでカスタムインスツルメンテーションを使用するには、以下の手順に従います。

  1. dd-trace --version を実行して、ツールのバージョンを取得します。
  2. 同じバージョンの Datadog.Trace NuGet パッケージ をアプリケーションに追加します。
  3. アプリケーションコードで、Datadog.Trace.Tracer.Instance プロパティを介してグローバルトレーサーにアクセスし、新しいスパンを作成します。

カスタムインスツルメンテーションのスパンやタグの追加方法については、.NET カスタムインスツルメンテーションのドキュメント を参照してください。

手動テスト API

注: 手動テスト API を使用するには、ターゲットの .NET プロジェクトに Datadog.Trace NuGet パッケージを追加することが必要です。

.NET プロジェクトで XUnit、NUnit、または MSTest を使用する場合、Test Optimization はそれらを自動的にインスツルメンテーションし、テスト結果を Datadog に送信します。サポートされていないテストフレームワークを使用する場合、または別のテストメカニズムを使用する場合は、代わりに API を使用してテスト結果を Datadog に報告できます。

この API は、テストモジュール、テストスイート、テストの 3 つの概念に基づいています。

テストモジュール

テストモジュールは、テストを含む .NET アセンブリを表します。

テストモジュールを開始するには、TestModule.Create() を呼び出し、テストが配置されているモジュール名または .NET アセンブリ名を渡してください。

すべてのテストが終了したら、module.Close() または module.CloseAsync() を呼び出してください。これにより、ライブラリは残りのすべてのテスト結果をバックエンドに強制的に送信します。

テストスイート

テストスイートは、一連のテストで構成されます。これらには、共通の初期化メソッドと終了メソッドがあり、いくつかの変数を共有できます。.NET では、通常、複数のテストメソッドを含むテストクラスまたはフィクスチャとして実装されます。テストスイートには、属性やエラー情報などの追加情報をオプションで含めることができます。

テストモジュールにテストスイートを作成するには、module.GetOrCreateSuite() を呼び出し、テストスイート名を渡します。

テストスイート内の関連するテストがすべて実行を完了したら suite.Close() を呼び出します。

テスト

各テストはテストスイート内で実行され、TestStatus.Pass、TestStatus.Fail、または TestStatus.Skip の 3 つのステータスのいずれかで終了する必要があります。

テストは、オプションで以下のような付加情報を持つことができます。

  • パラメーター
  • 属性
  • エラー情報
  • テスト特性
  • ベンチマークデータ

スイート内にテストを作成するには、suite.CreateTest() を呼び出し、テスト名を渡します。テストが終了したら、定義済みのステータスのいずれかを指定してtest.Close()を呼び出します。

コード例

次のコードは、API の簡単な使い方を表しています。

using System.Reflection;
using Datadog.Trace.Ci;

var module = TestModule.Create(Assembly.GetExecutingAssembly().GetName().Name ?? "(dyn_module)");
module.SetTag("ModuleTag", "Value");

var suite = module.GetOrCreateSuite("MySuite");
suite.SetTag("SuiteTag", 42);

var test = suite.CreateTest("Test01");
test.SetTag("TestTag", "Value");
test.SetParameters(new TestParameters
{
    Arguments = new Dictionary<string, object>
    {
        ["a"] = 42,
        ["b"] = 0,
    }
});
test.SetTraits(new Dictionary<string, List<string>>
{
    ["Category"] = new () { "UnitTest" }
});

try
{
    var a = 42;
    var b = 0;
    var c = a / b;
}
catch (Exception ex)
{
    test.SetErrorInfo(ex);
}

test.Close(TestStatus.Fail);
suite.Close();
await module.CloseAsync();

すべてのテストデータが Datadog に渡されるように、最後に必ず module.Close() または module.CloseAsync() を呼び出してください。

ベストプラクティス

テストセッション名 DD_TEST_SESSION_NAME

DD_TEST_SESSION_NAME を使用してテストセッションの名前と関連するテストグループを定義します。このタグの値の例は次のとおりです。

  • unit-tests
  • integration-tests
  • smoke-tests
  • flaky-tests
  • ui-tests
  • backend-tests

DD_TEST_SESSION_NAME が指定されていない場合、デフォルトで CI ジョブ名とテストコマンドになります。CI ジョブ名が利用できない場合は、テストコマンドが使用されます。

異なるテストグループを区別しやすくするため、テストセッション名はリポジトリ内で一意でなければなりません。

DD_TEST_SESSION_NAME を使用するタイミング

Datadog がテストセッション間の対応関係を確立するためにチェックするパラメーターのセットがあります。テストの実行に使用されるテストコマンドもその 1 つです。一時フォルダーなど、実行ごとに変化する文字列がテストコマンドに含まれる場合、Datadog はそれらのセッションを互いに無関係なものとみなします。たとえば、以下のような場合です。

  • dotnet test --temp-dir=/var/folders/t1/rs2htfh55mz9px2j4prmpg_c0000gq/T

テストコマンドが実行ごとに異なる場合、Datadog は DD_TEST_SESSION_NAME を使用することを推奨します。

参考資料