【发布时间】:2023-01-26 23:53:36
【问题描述】:
我想在我的 PowerShell 脚本中定义函数,并且能够在不执行脚本其余部分的情况下对函数进行 Pester 测试。有没有办法在不在单独的文件中定义函数的情况下执行此操作?
在下面的伪代码示例中,如何在不执行主要功能的情况下测试功能或函数?
脚本.ps1:
functionA
functionB
...
mainFunctionality
脚本.Tests.ps1:
BeforeAll {
. $PSScriptRoot/script.ps1 # This will execute the mainFunctionality, which is what I want to avoid
}
Describe 'functionA' {
# ... tests
}
我相信 Python,你可以通过将你的“mainFunctionality”包装在这个条件中来做到这一点,所以我在 Powershell 中寻找类似的东西。
if __name__ == '__main__':
mainFunctionality
【问题讨论】:
-
通过将
mainFunctionality移动到一个单独的文件中 :) -
使用 AST (
[System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$null, [ref]$errors)[System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/script.ps1", [ref]$null, [ref]$null)) 浏览脚本中的函数并调用它们。 -
您可以向脚本添加一个可选的开关参数以跳过“mainFunctionality”。包含用于测试的脚本时,使用 switch 参数调用它。
标签: powershell pester pester-5