如何在VSTS中配置构建规则,要求项目含单元测试否则构建失败?
Absolutely, you can set up build rules to fail builds when no unit tests are present or executed in your projects. Here’s a practical, step-by-step guide to implement this in the Azure DevOps (formerly VSTS) Web Portal:
Approach 1: Check for the Existence of Unit Test Projects
First, ensure your repository contains at least one unit test project (aligned with your team’s naming convention, like *Tests.csproj for .NET):
- Navigate to your project’s Pipelines > Builds and edit your existing build pipeline.
- Add a PowerShell task (or Bash if using Linux agents) early in your pipeline—before any test execution tasks.
- Paste this script into the task’s "Script" field, adjusting the filter to match your test project naming pattern:
# Search for test projects matching your team's convention $testProjects = Get-ChildItem -Path "$(Build.SourcesDirectory)" -Filter "*Tests.csproj" -Recurse if ($testProjects.Count -eq 0) { Write-Error "Error: No unit test projects found in the repository. Build aborted." exit 1 } else { Write-Host "Success: Found $($testProjects.Count) unit test project(s)." } - Ensure the task is set to Continue on error: No so any failure stops the build immediately.
Approach 2: Verify Unit Tests Are Actually Executed
Even if a test project exists, it might have no tests. Add this check after your test execution task to confirm tests ran successfully:
- After your test task (e.g., Visual Studio Test for .NET), add another PowerShell task.
- Use this script to parse test result files (adjust the XML path if using a non-.NET test framework):
# Locate test result files (.trx for .NET projects) $trxFiles = Get-ChildItem -Path "$(Build.TestResultsDirectory)" -Filter "*.trx" -Recurse if ($trxFiles.Count -eq 0) { Write-Error "Error: No test results were published. Build aborted." exit 1 } $totalTestsExecuted = 0 foreach ($file in $trxFiles) { $xmlContent = [xml](Get-Content $file.FullName) $tests = $xmlContent.TestRun.ResultSummary.Counters.Total $totalTestsExecuted += [int]$tests } if ($totalTestsExecuted -eq 0) { Write-Error "Error: No unit tests were executed. Build aborted." exit 1 } else { Write-Host "Success: $totalTestsExecuted unit tests executed." } - Again, set Continue on error: No for this task to enforce the rule.
Pro Tip: Combine Both Checks
For full coverage, use both approaches in your pipeline. This prevents edge cases where a test project exists but is empty, or isn’t configured to run in the build.
YAML Pipeline Note
If you’re using YAML-based pipelines, you can add these script tasks directly to your YAML definition using the powershell or bash task types, with the exact same logic as above.
内容的提问来源于stack exchange,提问作者David

