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

Pester 5.6.1中BeforeDiscovery加载数组无法在It/Context迭代的问题

问题原因与解决方案

核心问题在于Pester 5的Discovery阶段与Run阶段是完全隔离的执行上下文,且测试用例的收集仅在Discovery阶段完成:

  • BeforeDiscovery 属于Discovery阶段,在此定义的数组变量确实能在Run阶段被引用,但如果在Run阶段(比如外层It块内)尝试遍历数组生成新的It测试,这些动态生成的测试不会被Pester识别——因为Discovery阶段已经结束,不会再收集新的测试用例,最终导致相关测试被完全忽略。

正确实现方式

要基于BeforeDiscovery加载的数组生成动态测试,必须在Discovery阶段完成测试用例的定义,推荐两种实现方式:

方式1:使用-ForEach参数(Pester 5原生推荐)

BeforeDiscovery {
    # 在Discovery阶段加载数组数据
    $testItems = @("Item1", "Item2", "Item3")
}

Describe "Validate Array Items" -ForEach $testItems {
    It "Item '<_>' should match pattern" {
        $_ | Should -Match "^Item\d+$"
    }
}

方式2:在Discovery阶段用foreach循环生成测试

BeforeDiscovery {
    $testItems = @("Item1", "Item2", "Item3")
}

Describe "Validate Array Items" {
    # 此foreach在Discovery阶段执行,生成的It测试会被Pester正常收集
    foreach ($item in $testItems) {
        It "Item '$item' should match pattern" {
            $item | Should -Match "^Item\d+$"
        }
    }

    # 验证数组在Run阶段可正常引用
    It "Verify array exists in Run phase" {
        $testItems | Should -Not -BeNullOrEmpty
    }
}

错误写法的问题所在

如果你的代码是类似下面的结构,内层It块是在Run阶段(外层It的执行过程中)定义的,此时Pester已经完成了测试用例的收集工作,不会再处理这些动态生成的测试:

# 错误写法示例
BeforeDiscovery {
    $testItems = @("Item1", "Item2", "Item3")
}

Describe "Wrong Approach" {
    It "Attempt to generate tests in Run phase" {
        # 此foreach在Run阶段执行,生成的It测试不会被收集
        foreach ($item in $testItems) {
            It "Validate $item" {
                $item | Should -BeValid
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:52:09