约 2027 字

约 10 分钟

#Pester 单元测试

#简介

Pester 是 PowerShell 最常用的测试框架,用于编写和运行单元测试、集成测试。Pester 5 是当前的主要版本,测试文件通常以 .Tests.ps1 结尾。Pester 5 通常需要从 PowerShell Gallery 单独安装。

#安装 Pester

Install-Module Pester -Scope CurrentUser -Force
Get-Module Pester -ListAvailable

#基本结构

Describe '示例模块' {
    Context '正常输入' {
        It '计算两数之和' {
            1 + 1 | Should -Be 2
        }
    }
}

#Should 断言

Should 用于断言实际值是否符合预期,常用形式如下:

常用断言包括 Should -Be、-BeExactly、-BeTrue/-BeFalse、-BeNullOrEmpty、-Contain、-HaveCount、-Match 和 -Throw。

$result = 'Hello'
$result | Should -Match '^Hel'
@(1, 2, 3) | Should -HaveCount 3
{ throw 'failed' } | Should -Throw

#BeforeAll 和 AfterAll

BeforeAll 在测试开始前执行一次,AfterAll 在结束后执行一次,适合准备和清理资源:

BeforeAll {
    . (Join-Path $PSScriptRoot '../src/Math.ps1')
    $script:tempFile = Join-Path $TestDrive 'data.txt'
}

AfterAll {
    Remove-Item -LiteralPath $script:tempFile -ErrorAction SilentlyContinue
}

#测试 .ps1 函数

被测脚本 src/Math.ps1:

function Add-Numbers {
    param([int]$Left, [int]$Right)
    $Left + $Right
}

测试文件 tests/Math.Tests.ps1:

BeforeAll {
    . (Join-Path $PSScriptRoot '../src/Math.ps1')
}

Describe 'Add-Numbers' {
    It '返回两个整数之和' {
        Add-Numbers -Left 2 -Right 3 | Should -Be 5
    }

    It '支持负数' {
        Add-Numbers -Left -5 -Right 3 | Should -Be -2
    }
}

#运行测试

Invoke-Pester -Path ./tests -Output Detailed

在 CI 环境中可以使用 -CI 参数,输出更适合流水线的结果并设置退出码。

#注意事项

  • 测试文件命名建议使用 *.Tests.ps1,便于按目录批量运行。
  • 测试应独立,不依赖执行顺序或上一次测试留下的状态。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2