dotnet-test

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

.NET Test Execution

.NET 测试执行

Basic Test Commands

基础测试命令

bash
undefined
bash
undefined

Run all tests in solution

运行解决方案中的所有测试

dotnet test
dotnet test

Run tests in specific project

运行指定项目中的测试

dotnet test tests/MyApp.Tests/MyApp.Tests.csproj
dotnet test tests/MyApp.Tests/MyApp.Tests.csproj

Run without build (faster if already built)

跳过构建运行测试(若已构建则速度更快)

dotnet test --no-build
dotnet test --no-build

Run without restore

跳过还原运行测试

dotnet test --no-restore
undefined
dotnet test --no-restore
undefined

Test Filtering

测试筛选

By Name

按名称筛选

bash
undefined
bash
undefined

Filter by fully qualified name (contains)

按完全限定名称筛选(包含匹配)

dotnet test --filter "FullyQualifiedName~OrderService"
dotnet test --filter "FullyQualifiedName~OrderService"

Filter by test name (exact match)

按测试名称筛选(精确匹配)

dotnet test --filter "Name=CreateOrder_ValidInput_ReturnsOrder"
dotnet test --filter "Name=CreateOrder_ValidInput_ReturnsOrder"

Filter by display name

按显示名称筛选

dotnet test --filter "DisplayName~Create Order"
undefined
dotnet test --filter "DisplayName~Create Order"
undefined

By Category/Trait

按分类/特性筛选

bash
undefined
bash
undefined

Filter by trait (xUnit)

按特性筛选(xUnit)

dotnet test --filter "Category=Unit" dotnet test --filter "Category!=Integration"
dotnet test --filter "Category=Unit" dotnet test --filter "Category!=Integration"

Multiple trait filters

多特性筛选

dotnet test --filter "Category=Unit&Priority=High" dotnet test --filter "Category=Unit|Category=Integration"
undefined
dotnet test --filter "Category=Unit&Priority=High" dotnet test --filter "Category=Unit|Category=Integration"
undefined

By Class/Namespace

按类/命名空间筛选

bash
undefined
bash
undefined

Filter by class name

按类名筛选

dotnet test --filter "ClassName=OrderServiceTests"
dotnet test --filter "ClassName=OrderServiceTests"

Filter by namespace

按命名空间筛选

dotnet test --filter "FullyQualifiedName~MyApp.Tests.Services"
undefined
dotnet test --filter "FullyQualifiedName~MyApp.Tests.Services"
undefined

Complex Filters

复杂筛选

bash
undefined
bash
undefined

Combine with operators

组合运算符使用

& (and), | (or), ! (not), ~ (contains), = (equals)

&(且), |(或), !(非), ~(包含), =(等于)

Unit tests except slow ones

单元测试(排除慢测试)

dotnet test --filter "Category=Unit&Category!=Slow"
dotnet test --filter "Category=Unit&Category!=Slow"

All tests in namespace containing "Order"

命名空间中包含"Order"的所有测试(排除集成测试)

dotnet test --filter "FullyQualifiedName~Order&Category!=Integration"
undefined
dotnet test --filter "FullyQualifiedName~Order&Category!=Integration"
undefined

Test Output

测试输出

Verbosity Levels

详细程度级别

bash
undefined
bash
undefined

Quiet (minimal output)

安静模式(最少输出)

dotnet test --verbosity quiet dotnet test -v q
dotnet test --verbosity quiet dotnet test -v q

Normal (default)

正常模式(默认)

dotnet test --verbosity normal
dotnet test --verbosity normal

Detailed (shows all test names)

详细模式(显示所有测试名称)

dotnet test --verbosity detailed dotnet test -v d
dotnet test --verbosity detailed dotnet test -v d

Diagnostic (maximum output)

诊断模式(最大输出)

dotnet test --verbosity diagnostic
undefined
dotnet test --verbosity diagnostic
undefined

Logger Options

日志选项

bash
undefined
bash
undefined

Console logger with verbosity

带详细程度的控制台日志

dotnet test --logger "console;verbosity=detailed"
dotnet test --logger "console;verbosity=detailed"

TRX (Visual Studio Test Results)

TRX格式(Visual Studio测试结果)

dotnet test --logger trx
dotnet test --logger trx

JUnit format (for CI systems)

JUnit格式(适用于CI系统)

dotnet test --logger "junit;LogFileName=results.xml"
dotnet test --logger "junit;LogFileName=results.xml"

HTML report

HTML报告

dotnet test --logger "html;LogFileName=results.html"
dotnet test --logger "html;LogFileName=results.html"

Multiple loggers

多日志器

dotnet test --logger trx --logger "console;verbosity=detailed"
undefined
dotnet test --logger trx --logger "console;verbosity=detailed"
undefined

Results Directory

结果目录

bash
undefined
bash
undefined

Specify results output directory

指定结果输出目录

dotnet test --results-directory ./TestResults
undefined
dotnet test --results-directory ./TestResults
undefined

Code Coverage

代码覆盖率

Collect Coverage

收集覆盖率数据

bash
undefined
bash
undefined

Basic coverage collection

基础覆盖率收集

dotnet test --collect:"XPlat Code Coverage"
dotnet test --collect:"XPlat Code Coverage"

With Coverlet

使用Coverlet收集

dotnet test /p:CollectCoverage=true
dotnet test /p:CollectCoverage=true

Coverlet with specific format

使用Coverlet并指定格式

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

Multiple formats

多格式输出

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat="opencover,cobertura"
undefined
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat="opencover,cobertura"
undefined

Coverage Thresholds

覆盖率阈值

bash
undefined
bash
undefined

Fail if coverage below threshold

若覆盖率低于阈值则测试失败

dotnet test /p:CollectCoverage=true /p:Threshold=80
dotnet test /p:CollectCoverage=true /p:Threshold=80

Per-type thresholds

按类型设置阈值

dotnet test /p:CollectCoverage=true /p:ThresholdType=line /p:Threshold=80
undefined
dotnet test /p:CollectCoverage=true /p:ThresholdType=line /p:Threshold=80
undefined

Coverage Reports

覆盖率报告

bash
undefined
bash
undefined

Install report generator

安装报告生成器

dotnet tool install -g dotnet-reportgenerator-globaltool
dotnet tool install -g dotnet-reportgenerator-globaltool

Generate HTML report

生成HTML报告

reportgenerator -reports:coverage.cobertura.xml -targetdir:coveragereport
undefined
reportgenerator -reports:coverage.cobertura.xml -targetdir:coveragereport
undefined

Parallel Execution

并行执行

bash
undefined
bash
undefined

Control parallelism

启用并行执行

dotnet test --parallel
dotnet test --parallel

Limit parallel workers

限制并行工作进程数

dotnet test -- RunConfiguration.MaxCpuCount=4
dotnet test -- RunConfiguration.MaxCpuCount=4

Disable parallel execution

禁用并行执行

dotnet test -- RunConfiguration.DisableParallelization=true
undefined
dotnet test -- RunConfiguration.DisableParallelization=true
undefined

Test Timeouts

测试超时

bash
undefined
bash
undefined

Set test timeout (milliseconds)

设置测试会话超时(毫秒)

dotnet test -- RunConfiguration.TestSessionTimeout=60000

```csharp
// Per-test timeout (xUnit)
[Fact(Timeout = 5000)]
public void SlowTest() { }

// Per-test timeout (NUnit)
[Test, Timeout(5000)]
public void SlowTest() { }
dotnet test -- RunConfiguration.TestSessionTimeout=60000

```csharp
// 单测试超时(xUnit)
[Fact(Timeout = 5000)]
public void SlowTest() { }

// 单测试超时(NUnit)
[Test, Timeout(5000)]
public void SlowTest() { }

Configuration Files

配置文件

runsettings

runsettings文件

xml
<!-- test.runsettings -->
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <MaxCpuCount>4</MaxCpuCount>
    <ResultsDirectory>./TestResults</ResultsDirectory>
    <TestSessionTimeout>600000</TestSessionTimeout>
  </RunConfiguration>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="XPlat Code Coverage">
        <Configuration>
          <Format>cobertura</Format>
          <Exclude>[*]*.Migrations.*</Exclude>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>
bash
undefined
xml
<!-- test.runsettings -->
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <MaxCpuCount>4</MaxCpuCount>
    <ResultsDirectory>./TestResults</ResultsDirectory>
    <TestSessionTimeout>600000</TestSessionTimeout>
  </RunConfiguration>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="XPlat Code Coverage">
        <Configuration>
          <Format>cobertura</Format>
          <Exclude>[*]*.Migrations.*</Exclude>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>
bash
undefined

Use runsettings file

使用runsettings文件

dotnet test --settings test.runsettings
undefined
dotnet test --settings test.runsettings
undefined

Test Failure Analysis

测试失败分析

Common Failure Patterns

常见失败模式

PatternCauseFix
Assert.Equal failedExpected != ActualCheck logic, verify test data
NullReferenceExceptionNull not handledAdd null checks, verify setup
TimeoutExceptionTest too slowOptimize or increase timeout
ObjectDisposedExceptionUsing disposed objectFix lifetime management
InvalidOperationExceptionInvalid stateCheck test setup/order
模式原因修复方案
Assert.Equal 失败预期值与实际值不匹配检查逻辑,验证测试数据
NullReferenceException未处理空引用添加空值检查,验证测试初始化
TimeoutException测试执行过慢优化测试或增加超时时间
ObjectDisposedException使用已释放的对象修复对象生命周期管理
InvalidOperationException无效状态检查测试初始化/执行顺序

Debugging Failed Tests

调试失败测试

bash
undefined
bash
undefined

Run single failing test with detailed output

运行单个失败测试并显示详细输出

dotnet test --filter "FullyQualifiedName~FailingTest" -v d
dotnet test --filter "FullyQualifiedName~FailingTest" -v d

Enable blame mode to catch hangs

启用Blame模式捕获挂起

dotnet test --blame
dotnet test --blame

Blame with hang detection

启用Blame模式并检测挂起(超时60秒)

dotnet test --blame-hang --blame-hang-timeout 60s
undefined
dotnet test --blame-hang --blame-hang-timeout 60s
undefined

Watch Mode

监听模式

bash
undefined
bash
undefined

Run tests on file changes

文件变更时自动运行测试

dotnet watch test
dotnet watch test

Watch specific project

监听指定项目

dotnet watch --project tests/MyApp.Tests test
dotnet watch --project tests/MyApp.Tests test

Watch with filter

监听并按筛选条件运行测试

dotnet watch test --filter "Category=Unit"
undefined
dotnet watch test --filter "Category=Unit"
undefined

CI/CD Integration

CI/CD集成

Exit Codes

退出代码

CodeMeaning
0All tests passed
1Tests failed
2Command line error
代码含义
0所有测试通过
1测试失败
2命令行错误

CI Examples

CI示例

bash
undefined
bash
undefined

Azure DevOps

Azure DevOps

  • task: DotNetCoreCLI@2 inputs: command: test arguments: '--configuration Release --logger trx'
  • task: DotNetCoreCLI@2 inputs: command: test arguments: '--configuration Release --logger trx'

GitHub Actions

GitHub Actions

  • run: dotnet test --configuration Release --logger "trx;LogFileName=test-results.trx"

See [test-filtering.md](test-filtering.md) for advanced filtering patterns.
  • run: dotnet test --configuration Release --logger "trx;LogFileName=test-results.trx"

查看 [test-filtering.md](test-filtering.md) 获取高级筛选模式。