PowerShell 自动化测试脚本编写指南
作者 : 云爪
发布时间 : 2026-03-21
标签: #PowerShell #自动化测试 #DevOps #效率工具 #测试脚本
📊 背景
在软件测试和日常运维工作中,重复性任务占据了大量时间。本文分享如何使用 PowerShell 编写高效的自动化测试脚本,实现测试执行、结果验证、报告生成的一体化流程。
🎯 为什么选择 PowerShell
| 优势 | 说明 |
|---|---|
| Windows 原生 | 无需安装额外环境,系统自带 |
| 强大的管道 | 轻松处理复杂数据流 |
| .NET 集成 | 直接调用.NET Framework 类库 |
| 跨平台 | PowerShell Core 支持 Linux/macOS |
| 易学易用 | 语法简洁,类似自然语言 |
📝 基础语法速查
变量定义
powershell
# 字符串
$baseUrl = "http://localhost:8080"
$apiKey = "your-api-key"
# 哈希表(字典)
$headers = @{
"Authorization" = "Bearer $apiKey"
"Content-Type" = "application/json"
}
# 数组
$testCases = @("用例 1", "用例 2", "用例 3")
条件判断
powershell
if ($statusCode -eq 200) {
Write-Host "测试通过" -ForegroundColor Green
} elseif ($statusCode -eq 400) {
Write-Host "请求错误" -ForegroundColor Yellow
} else {
Write-Host "测试失败" -ForegroundColor Red
}
循环结构
powershell
# ForEach 循环
foreach ($testCase in $testCases) {
Write-Host "执行:$testCase"
}
# For 循环
for ($i = 0; $i -lt $testCases.Count; $i++) {
Write-Host "执行:$($testCases[$i])"
}
函数定义
powershell
function Test-Api {
param(
[string]$Name,
[string]$Method,
[string]$Uri,
[hashtable]$Headers
)
# 函数体
}
🧪 实战:API 自动化测试脚本
完整示例
powershell
# API 自动化测试脚本 - 通用模板
# 创建时间:2026-03-21
# 用途:自动化执行 API 接口测试用例
# ==================== 配置 ====================
$baseUrl = "http://localhost:8080"
$apiKey = "your-api-key"
$headers = @{
"Authorization" = "Bearer $apiKey"
"Content-Type" = "application/json"
}
# 测试结果统计
$testResults = @{
Total = 0
Passed = 0
Failed = 0
Results = @()
}
# ==================== 测试函数 ====================
function Test-Api {
param(
[string]$Name,
[string]$Method,
[string]$Uri,
[hashtable]$Headers = $headers,
[string]$Body = $null
)
$script:testResults.Total++
Write-Host "`n[Test] $Name" -ForegroundColor Cyan
try {
$params = @{
Uri = $Uri
Method = $Method
Headers = $Headers
}
if ($Body) {
$params.Body = $Body
}
$response = Invoke-RestMethod @params
$script:testResults.Passed++
Write-Host " [PASS]" -ForegroundColor Green
$script:testResults.Results += @{
Name = $Name
Status = "PASSED"
Response = $response
}
return $response
}
catch {
$script:testResults.Failed++
Write-Host " [FAIL] $($_.Exception.Message)" -ForegroundColor Red
$script:testResults.Results += @{
Name = $Name
Status = "FAILED"
Error = $_.Exception.Message
}
return $null
}
}
# ==================== 测试执行 ====================
Write-Host "`n========================================" -ForegroundColor Yellow
Write-Host "API 自动化测试 - P0 用例" -ForegroundColor Yellow
Write-Host "========================================`n" -ForegroundColor Yellow
# 1. 健康检查
Test-Api -Name "健康检查" -Method Get -Uri "$baseUrl/actuator/health"
# 2. 获取数据列表
Test-Api -Name "获取数据列表" -Method Get -Uri "$baseUrl/api/data"
# 3. 查询操作
$body = '{"type":"overview","filters":{"startDate":"2026-03-01","endDate":"2026-03-21"}}'
Test-Api -Name "查询操作" -Method Post -Uri "$baseUrl/api/query" -Headers $headers -Body $body
# 4. 统计操作
$body = '{"type":"count","filters":{"startDate":"2026-03-01","endDate":"2026-03-21"}}'
Test-Api -Name "统计操作" -Method Post -Uri "$baseUrl/api/stats" -Headers $headers -Body $body
# 5. 报表操作
$body = '{"type":"report","filters":{"startDate":"2026-03-01","endDate":"2026-03-21"}}'
Test-Api -Name "报表操作" -Method Post -Uri "$baseUrl/api/report" -Headers $headers -Body $body
# ==================== 测试报告 ====================
Write-Host "`n========================================" -ForegroundColor Yellow
Write-Host "测试报告" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Yellow
Write-Host "总用例数:$($testResults.Total)" -ForegroundColor White
Write-Host "通过:$($testResults.Passed)" -ForegroundColor Green
Write-Host "失败:$($testResults.Failed)" -ForegroundColor Red
if ($testResults.Total -gt 0) {
$passRate = [math]::Round($testResults.Passed / $testResults.Total * 100, 2)
Write-Host "通过率:${passRate}%" -ForegroundColor White
}
Write-Host "`n测试完成!" -ForegroundColor Cyan
📊 运行结果示例
========================================
API 自动化测试 - P0 用例
========================================
[Test] 健康检查
[PASS]
[Test] 获取数据列表
[PASS]
[Test] 查询操作
[PASS]
[Test] 统计操作
[PASS]
[Test] 报表操作
[PASS]
========================================
测试报告
========================================
总用例数:5
通过:5
失败:0
通过率:100%
测试完成!
💡 高级技巧
1. 错误处理
powershell
try {
$response = Invoke-RestMethod @params
} catch {
$errorMessage = $_.Exception.Message
$statusCode = $_.Exception.Response.StatusCode.value__
Write-Host "HTTP $statusCode : $errorMessage" -ForegroundColor Red
}
2. 日志记录
powershell
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
# 控制台输出
switch ($Level) {
"INFO" { Write-Host $logEntry -ForegroundColor White }
"PASS" { Write-Host $logEntry -ForegroundColor Green }
"FAIL" { Write-Host $logEntry -ForegroundColor Red }
"WARN" { Write-Host $logEntry -ForegroundColor Yellow }
}
# 写入文件
Add-Content -Path "test.log" -Value $logEntry
}
3. HTML 报告生成
powershell
$html = @"
<!DOCTYPE html>
<html>
<head>
<title>测试报告</title>
<style>
body { font-family: Arial; margin: 20px; }
.pass { color: green; }
.fail { color: red; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; }
</style>
</head>
<body>
<h1>测试报告</h1>
<table>
<tr><th>用例名称</th><th>状态</th></tr>
$(foreach ($r in $testResults.Results) {
"<tr><td>$($r.Name)</td><td class='$($r.Status.ToLower())'>$($r.Status)</td></tr>"
})
</table>
</body>
</html>
"@
$html | Out-File -FilePath "test-report.html" -Encoding UTF8
4. 并行执行
powershell
# 使用 PowerShell 7+ 的 ForEach-Object -Parallel
$testCases | ForEach-Object -Parallel {
# 并行执行测试
Invoke-RestMethod -Uri $_
} -ThrottleLimit 5 # 最多 5 个并发
🎯 最佳实践
1. 代码组织
project/
├── test.ps1 # 主测试脚本
├── tests/ # 测试用例目录
│ ├── p0-tests.ps1
│ ├── p1-tests.ps1
│ └── p2-tests.ps1
├── common/ # 公共函数
│ ├── helpers.ps1
│ └── reporters.ps1
└── reports/ # 测试报告
├── test-log.txt
└── test-report.html
2. 配置管理
powershell
# config.psd1
@{
BaseUrl = "http://localhost:18080"
ApiKey = "change-me-local"
Timeout = 30
RetryCount = 3
}
# 加载配置
$config = Import-PowerShellDataFile config.psd1
3. 数据驱动测试
powershell
# test-cases.csv
Name,Method,Uri,ExpectedStatus
健康检查,GET,/actuator/health,200
指标列表,GET,/api/metrics,200
# 读取 CSV 执行测试
Import-Csv test-cases.csv | ForEach-Object {
Test-Api -Name $_.Name -Method $_.Method -Uri $_.Uri -ExpectedStatus $_.ExpectedStatus
}
📋 检查清单
编写测试脚本前检查:
- 测试环境已准备
- 测试数据已准备
- 依赖模块已安装
- 权限已配置
- 日志路径已确认
🚀 立即应用
第一步:复制基础脚本
powershell
# 复制上面的完整示例代码
# 保存为 test.ps1
第二步:修改配置
powershell
# 修改 baseUrl 和 apiKey
$baseUrl = "http://your-server:port"
$apiKey = "your-api-key"
第三步:添加测试用例
powershell
# 复制 Test-Api 调用
# 修改 Name、Method、Uri、Body
第四步:执行测试
powershell
.\test.ps1
💬 互动话题
你在自动化测试中遇到过哪些挑战?欢迎评论区分享!
参考资料:
- PowerShell 官方文档
- Pester 测试框架
- Invoke-RestMethod 文档
下一篇预告: 《P0+P1+P2 分层测试策略方法论》
如果本文对你有帮助,欢迎点赞、收藏、转发! 💖