dotnet-test
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese.NET Test Execution
.NET 测试执行
Basic Test Commands
基础测试命令
bash
undefinedbash
undefinedRun 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
undefineddotnet test --no-restore
undefinedTest Filtering
测试筛选
By Name
按名称筛选
bash
undefinedbash
undefinedFilter 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"
undefineddotnet test --filter "DisplayName~Create Order"
undefinedBy Category/Trait
按分类/特性筛选
bash
undefinedbash
undefinedFilter 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"
undefineddotnet test --filter "Category=Unit&Priority=High"
dotnet test --filter "Category=Unit|Category=Integration"
undefinedBy Class/Namespace
按类/命名空间筛选
bash
undefinedbash
undefinedFilter by class name
按类名筛选
dotnet test --filter "ClassName=OrderServiceTests"
dotnet test --filter "ClassName=OrderServiceTests"
Filter by namespace
按命名空间筛选
dotnet test --filter "FullyQualifiedName~MyApp.Tests.Services"
undefineddotnet test --filter "FullyQualifiedName~MyApp.Tests.Services"
undefinedComplex Filters
复杂筛选
bash
undefinedbash
undefinedCombine 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"
undefineddotnet test --filter "FullyQualifiedName~Order&Category!=Integration"
undefinedTest Output
测试输出
Verbosity Levels
详细程度级别
bash
undefinedbash
undefinedQuiet (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
undefineddotnet test --verbosity diagnostic
undefinedLogger Options
日志选项
bash
undefinedbash
undefinedConsole 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"
undefineddotnet test --logger trx --logger "console;verbosity=detailed"
undefinedResults Directory
结果目录
bash
undefinedbash
undefinedSpecify results output directory
指定结果输出目录
dotnet test --results-directory ./TestResults
undefineddotnet test --results-directory ./TestResults
undefinedCode Coverage
代码覆盖率
Collect Coverage
收集覆盖率数据
bash
undefinedbash
undefinedBasic 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"
undefineddotnet test /p:CollectCoverage=true /p:CoverletOutputFormat="opencover,cobertura"
undefinedCoverage Thresholds
覆盖率阈值
bash
undefinedbash
undefinedFail 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
undefineddotnet test /p:CollectCoverage=true /p:ThresholdType=line /p:Threshold=80
undefinedCoverage Reports
覆盖率报告
bash
undefinedbash
undefinedInstall 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
undefinedreportgenerator -reports:coverage.cobertura.xml -targetdir:coveragereport
undefinedParallel Execution
并行执行
bash
undefinedbash
undefinedControl 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
undefineddotnet test -- RunConfiguration.DisableParallelization=true
undefinedTest Timeouts
测试超时
bash
undefinedbash
undefinedSet 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
undefinedxml
<!-- 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
undefinedUse runsettings file
使用runsettings文件
dotnet test --settings test.runsettings
undefineddotnet test --settings test.runsettings
undefinedTest Failure Analysis
测试失败分析
Common Failure Patterns
常见失败模式
| Pattern | Cause | Fix |
|---|---|---|
| Assert.Equal failed | Expected != Actual | Check logic, verify test data |
| NullReferenceException | Null not handled | Add null checks, verify setup |
| TimeoutException | Test too slow | Optimize or increase timeout |
| ObjectDisposedException | Using disposed object | Fix lifetime management |
| InvalidOperationException | Invalid state | Check test setup/order |
| 模式 | 原因 | 修复方案 |
|---|---|---|
| Assert.Equal 失败 | 预期值与实际值不匹配 | 检查逻辑,验证测试数据 |
| NullReferenceException | 未处理空引用 | 添加空值检查,验证测试初始化 |
| TimeoutException | 测试执行过慢 | 优化测试或增加超时时间 |
| ObjectDisposedException | 使用已释放的对象 | 修复对象生命周期管理 |
| InvalidOperationException | 无效状态 | 检查测试初始化/执行顺序 |
Debugging Failed Tests
调试失败测试
bash
undefinedbash
undefinedRun 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
undefineddotnet test --blame-hang --blame-hang-timeout 60s
undefinedWatch Mode
监听模式
bash
undefinedbash
undefinedRun 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"
undefineddotnet watch test --filter "Category=Unit"
undefinedCI/CD Integration
CI/CD集成
Exit Codes
退出代码
| Code | Meaning |
|---|---|
| 0 | All tests passed |
| 1 | Tests failed |
| 2 | Command line error |
| 代码 | 含义 |
|---|---|
| 0 | 所有测试通过 |
| 1 | 测试失败 |
| 2 | 命令行错误 |
CI Examples
CI示例
bash
undefinedbash
undefinedAzure 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) 获取高级筛选模式。