【问题标题】:Is there any way to test functions in a PowerShell script without executing the script?有没有什么方法可以在不执行脚本的情况下测试 PowerShell 脚本中的函数?
【发布时间】: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

参考:What does if __name__ == "__main__": do?

【问题讨论】:

  • 通过将 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


【解决方案1】:

是的,您可以使用 Invoke-Expression cmdlet 在不执行脚本的情况下测试 PowerShell 脚本中的函数。此 cmdlet 允许您像执行命令一样执行字符串。 例如,如果您的脚本中有一个名为 Test-Function 的函数,您可以使用以下命令对其进行测试:Invoke-Expression -Command "Test-Function"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多