이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Test Optimization is not available in the selected site () at this time.

Compatibility

For a list of supported runtimes and platforms, see .NET Framework Compatibility and .NET/.NET Core Compatiblity.

Supported test frameworks:

Test FrameworkVersion
xUnit>= 2.2
NUnit>= 3.0
MsTestV2>= 14
BenchmarkDotNet>= 0.13.2

Configuring reporting method

To report test results to Datadog, you need to configure the Datadog .NET library:

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

If you are using auto-instrumentation for one of these providers, you can skip the rest of the setup steps below.

Agentless mode is available in Datadog .NET library versions >= 2.5.1
GitHub Actions나 CircleCI와 같이 기본 작업자 노드에 액세스하지 않고 클라우드 CI 공급자를 사용할 경우, 라이브러리를 구성해 에이전트리스 모드로 사용하세요. 이 모드를 이용하려면 다음 환경 변수를 설정하세요.
DD_CIVISIBILITY_AGENTLESS_ENABLED=true (필수)
에이전트리스 모드 활성화 또는 비활성화
기본값: false
DD_API_KEY (필수)
테스트 결과를 업로드하는 데 사용되는 Datadog API 키
기본값: (empty)

추가로 데이터를 보낼 Datadog 사이트를 구성하세요.

DD_SITE (필수)
결과를 업로드할 Datadog 사이트
기본값: datadoghq.com

Jenkins 또는 자체 관리형 GitLab CI와 같은 온프레미스 CI 공급자에서 테스트를 실행하는 경우, 에이전트 설치 지침에 따라 각 작업자 노드에 Datadog 에이전트를 설치합니다. 자동으로 테스트 결과를 로그기본 호트스 메트릭과 연결할 수 있기 때문에 이 옵션을 추천합니다.

쿠버네티스 실행기를 사용하는 경우 Datadog에서는 Datadog 연산자를 사용할 것을 권고합니다. 연산자에는 Datadog 허용 제어기가 포함되어 있어 빌드 파드에 자동으로 추적기 라이브러리를 삽입합니다. 참고: Datadog 연산자를 사용할 경우 허용 제어기가 작업을 해주기 때문에 추적기 라이브러리를 다운로드 받고 삽입할 필요가 없습니다. 따라서 아래 해당 단계를 건너뛰어도 됩니다. 그러나 테스트 가시화 기능을 사용할 때 필요한 파드의 환경 변수나 명령줄 파라미터는 설정해야 합니다.

쿠버네티스를 사용하지 않거나 Datadog 허용 제어기를 사용할 수 없고 CI 공급자가 컨테이너 기반 실행기를 사용하는 경우, 추적기를 실행하는 빌드 컨테이너에서 환경 변수 DD_TRACE_AGENT_URL(기본값 http://localhost:8126)를 해당 컨테이너 내에서 액세스할 수 있는 엔드포인트로 설정합니다. 참고: 빌드 내에서 localhost를 사용하면 기본 작업자 노드나 에이전트를 실행하는 컨테이너를 참조하지 않고 컨테이너 자체를 참조합니다.

DD_TRACE_AGENT_URL 은 프로토콜과 포트(예: http://localhost:8126)를 포함하고 DD_AGENT_HOSTDD_TRACE_AGENT_PORT보다 우선하며, CI Visibility를 위해 Datadog 에이전트의 URL을 설정하는 데 권장되는 설정 파라미터입니다.

Datdog 에이전트에 연결하는 데 아직 문제가 있다면 에이전트리스 모드를 사용해 보세요. 참고: 이 방법을 사용할 경우 테스트가 로그인프라스트럭처 메트릭과 상관 관계를 수립하지 않습니다.

Installing the .NET tracer CLI

Install or update the dd-trace command using one of the following ways:

Instrumenting tests

Note: For BenchmarkDotNet follow these instructions.

To instrument your test suite, prefix your test command with dd-trace ci run, providing the name of the service or library under test as the --dd-service parameter, and the environment where tests are being run (for example, local when running tests on a developer workstation, or ci when running them on a CI provider) as the --dd-env parameter. For example:

By using dotnet test:

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

By using VSTest.Console.exe:

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

All tests are automatically instrumented.

Compatibility with Microsoft.CodeCoverage nuget package

Since Microsoft.CodeCoverage version 17.2.0 Microsoft introduced dynamic instrumentation using the .NET CLR Profiling API enabled by default only on Windows. Datadog’s automatic instrumentation relies on the .NET CLR Profiling API. This API allows only one subscriber (for example, dd-trace). The use of CodeCoverage dynamic instrumentation breaks the automatic test instrumentation.

The solution is to switch from dynamic instrumentation to static instrumentation. Modify your .runsettings file with the following configuration knobs:

<?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>

Configuration settings

You can change the default configuration of the CLI by using command line arguments or environment variables. For a full list of configuration settings, run:

dd-trace ci run --help

The following list shows the default values for key configuration settings:

--dd-service
Name of the service or library under test.
Environment variable: DD_SERVICE
Default: The repository name
Example: my-dotnet-app
--dd-env
Name of the environment where tests are being run.
Environment variable: DD_ENV
Default: none
Examples: local, ci
--agent-url
Datadog Agent URL for trace collection in the form http://hostname:port.
Environment variable: DD_TRACE_AGENT_URL
Default: http://localhost:8126

For more information about service and env reserved tags, see Unified Service Tagging. All other Datadog Tracer configuration options can also be used.

Adding custom tags to tests

To add custom tags to tests, configure custom instrumentation first.

You can add custom tags to your tests by using the current active span:

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

To create filters or group by fields for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the .NET custom instrumentation documentation.

Adding custom measures to tests

To add custom measures to tests, configure custom instrumentation first.

Just like tags, you can add custom measures to your tests by using the current active span:

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

To create filters or visualizations for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the .NET custom instrumentation documentation.

Read more about custom Measures in the Add Custom Measures Guide.

Reporting code coverage

When code coverage is available, the Datadog Tracer (v2.31.0 or later) reports it under the test.code_coverage.lines_pct tag for your test sessions.

If you are using Coverlet to compute your code coverage, indicate the path to the report file in the DD_CIVISIBILITY_EXTERNAL_CODE_COVERAGE_PATH environment variable when running dd-trace. The report file must be in the OpenCover or Cobertura formats. Alternatively, you can enable the Datadog Tracer’s built-in code coverage calculation with the DD_CIVISIBILITY_CODE_COVERAGE_ENABLED=true environment variable.

Note: When using Test Impact Analysis, the tracer’s built-in code coverage is enabled by default.

You can see the evolution of the test coverage in the Coverage tab of a test session.

For more information about exclusion options, see Code Coverage.

Instrumenting BenchmarkDotNet tests

To instrument your benchmark tests, you need to:

  1. Add the Datadog.Trace.BenchmarkDotNet NuGet package to your project (for example, using dotnet add package Datadog.Trace.BenchmarkDotNet).
  2. Configure your project to use the Datadog.Trace.BenchmarkDotNet exporter using the DatadogDiagnoser attribute or the WithDatadog() extension method. For example:
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. Configure the reporting method.
  2. Run the benchmark project as you normally do, all benchmark tests will be automatically instrumented.

Datadog은 Git 정보를 사용하여 테스트 결과를 시각화하고 리포지토리, 브랜치, 커밋별로 그룹화합니다. Git 메타데이터는 CI 공급자 환경 변수와 프로젝트 경로의 로컬 .git 폴더(사용 가능한 경우)에서 테스트 계측으로 자동 수집합니다.

지원되지 않는 CI 공급자이거나 .git 폴더가 없는 상태에서 테스트를 실행하는 경우, 환경 변수를 사용하여 Git 정보를 수동으로 설정할 수 있습니다. 해당 환경 변수는 자동 탐지된 정보보다 우선합니다. 다음 환경 변수를 설정하여 Git 정보를 제공합니다.

DD_GIT_REPOSITORY_URL
코드가 저장된 리포지토리 URL입니다. HTTP, SSH URL이 모두 지원됩니다.
예시: git@github.com:MyCompany/MyApp.git, https://github.com/MyCompany/MyApp.git
DD_GIT_BRANCH
테스트 중인 Git 브랜치입니다. 대신 태그 정보를 제공하는 경우 비워 둡니다.
예시: develop
DD_GIT_TAG
테스트 중인 Git 태그입니다(해당되는 경우). 대신 브랜치 정보를 제공하는 경우 비워 둡니다.
예시: 1.0.1
DD_GIT_COMMIT_SHA
전체 커밋 해시입니다.
예시: a18ebf361cc831f5535e58ec4fae04ffd98d8152
DD_GIT_COMMIT_MESSAGE
커밋 메시지입니다.
예시: Set release number
DD_GIT_COMMIT_AUTHOR_NAME
커밋 작성자 이름입니다.
예시: John Smith
DD_GIT_COMMIT_AUTHOR_EMAIL
커밋 작성자 이메일입니다.
예시: john@example.com
DD_GIT_COMMIT_AUTHOR_DATE
ISO 8601 형식의 커밋 작성자 날짜입니다.
예시: 2021-03-12T16:00:28Z
DD_GIT_COMMIT_COMMITTER_NAME
커밋 커미터 이름입니다.
예시: Jane Smith
DD_GIT_COMMIT_COMMITTER_EMAIL
커밋 커미터 이메일입니다.
예시: jane@example.com
DD_GIT_COMMIT_COMMITTER_DATE
ISO 8601 형식의 커밋 커미터 날짜입니다.
예시: 2021-03-12T16:00:28Z

Custom instrumentation

Note: Your custom instrumentation setup depends on the dd-trace version. To use the custom instrumentation, you must keep the package versions for dd-trace and Datadog.Trace NuGet packages in sync.

To use the custom instrumentation in your .NET application:

  1. Execute dd-trace --version to get the version of the tool.
  2. Add the Datadog.Trace NuGet package with the same version to your application.
  3. In your application code, access the global tracer through the Datadog.Trace.Tracer.Instance property to create new spans.

For more information about how to add spans and tags for custom instrumentation, see the .NET Custom Instrumentation documentation.

Manual testing API

Note: To use the manual testing API, you must add the Datadog.Trace NuGet package in the target .NET project.

If you use XUnit, NUnit, or MSTest with your .NET projects, Test Optimization automatically instruments them and sends the test results to Datadog. If you use an unsupported testing framework or if you have a different testing mechanism, you can instead use the API to report test results to Datadog.

The API is based around three concepts: test module, test suites, and tests.

Test module

A test module represents the .NET assembly that includes the tests.

To start a test module, call TestModule.Create() and pass the name of the module or .NET assembly name where the tests are located.

When all your tests have finished, call module.Close() or module.CloseAsync(), which forces the library to send all remaining test results to the backend.

Test suites

A test suite comprises a set of tests. They can have a common initialization and teardown methods and share some variables. In .NET, they are usually implemented as a Test class or fixture containing multiple test methods. A test suite can optionally have additional information like attributes or error information.

Create test suites in the test module by calling module.GetOrCreateSuite() and passing the name of the test suite.

Call suite.Close() when all the related tests in the suite have finished their execution.

Tests

Each test runs inside a suite and must end in one of these three statuses: TestStatus.Pass, TestStatus.Fail, or TestStatus.Skip.

A test can optionally have additional information like:

  • Parameters
  • Attributes
  • Error information
  • Test traits
  • Benchmark data

Create tests in a suite by calling suite.CreateTest() and passing the name of the test. When a test ends, call test.Close() with one of the predefined statuses.

Code example

The following code represents a simple usage of the 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();

Always call module.Close() or module.CloseAsync() at the end so that all the test data is flushed to Datadog.

Further reading