首页 > 解决方案 > 如何在 Pester 5 中为嵌套函数定义“It”测试?

问题描述

给定一个带有函数和嵌套函数的 PowerShell 脚本 (.ps1)。函数“内部”不应移动到外部范围,因此不应导出。如何为“内部”功能定义“It”测试(希望不修改代码)?

使用:PS核心7.1.4:

Function Outer {
    Function Inner {
        # ...
    }
    # ...
}

使用:纠缠 5.3.0:

Describe "A" {
    It "A" { Outer } | Should -be $null  # OK
    It "B" { Inner } | Should -be $null  # ERROR
}

标签: powershellpesterpester-5

解决方案


如果你真的必须这样做,有一种方法,但它涉及通过抽象语法树进行搜索。这可能有点复杂,但它可以完成工作。

所以你有这样定义的功能:

Function Outer {
    Function Inner {
        # ...
    }
    # ...
}

你可以找到如下scriptblock的函数:Inner

$outerCommandInfo = Get-Command -Name 'Outer'
$innerDefinition = $outerCommandInfo.ScriptBlock.Ast.FindAll( { param($ast) $ast -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) | ? Name -eq 'Inner'
$innerScriptBlock = $innerDefinition.Body.GetScriptBlock()

现在,在$innerScriptBlock变量中你有Inner函数的定义。您可以使用调用运算符调用它,或者简单地调用它$innerScriptBlock.Invoke()

传递参数和测试它会有点棘手。

Describe "A" {
    BeforeAll {
        # the code above
    }

    It "A" { Outer } | Should -be $null  # OK
    It "B" { & $innerScriptBlock } | Should -be $null  # OK?
}

推荐阅读