You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Pester v5中如何处理点源?避免执行非测试代码

测试单脚本中的函数(不创建模块/额外脚本)

场景说明

我需要测试单个脚本GetSomething.ps1里的Get-Something函数,但不想创建额外的.psm1模块或辅助脚本。该脚本内容如下:

# file GetSomething.ps1
function Get-Something # this is testable with pester
{
  'something'
}
# Some-Other-Function or call that takes very long or can't be run in Pester.
Do-Something-Expensive-NotTestable
Get-Something

传统点源导入的问题

按照Pester文档的常规做法,通过点源导入脚本会执行整个脚本内容,导致其中无法在测试环境运行的耗时代码Do-Something-Expensive-NotTestable也被执行,测试脚本示例如下:

#file GetSomething.Tests.ps1
BeforeAll {
  . $PSScriptRoot\GetSomething.ps1
}

Describe 'Get-Something' {
  It 'Gets something' {
      Get-Something | Should -Be 'something'
  }
}

Pester v5中的优化方案

之前找到的最佳方案是通过AST提取函数定义,避免执行脚本中的其他代码。在Pester v5中,这个方法依然是高效可行的优化方式,修改后的测试脚本如下:

BeforeAll {
  function Get-Functions($filePath)
  {
      $script = Get-Command $filePath
      return $script.ScriptBlock.AST.FindAll({ $args[0] -is [Management.Automation.Language.FunctionDefinitionAst] }, $false)
  }

  Get-Functions $PSScriptRoot\GetSomething.ps1 | Invoke-Expression
}

Describe 'Get-Something' {
  It 'Gets something' {
      Get-Something | Should -Be 'something'
  }
}

该方法通过PowerShell的抽象语法树(AST)扫描脚本文件,仅提取其中的函数定义并执行,不会触发脚本里的其他命令,完美解决了耗时代码干扰测试的问题。我平时更习惯用.psm1模块,但偶尔会把函数和脚本逻辑放在同一个文件里,这个方案能满足这种场景下的独立测试需求。

内容的提问来源于stack exchange,提问作者tomwaitforitmy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:33:11