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

如何获取Start-Job启动的Pester测试任务的运行结果

你之前的写法只获取了Pester的输出日志,没有捕获测试结果对象或进程退出码,所以外层Pester无法判断内部测试的执行状态,可通过以下两种方案解决:


方案1:使用-PassThru返回测试结果对象(最通用)

Invoke-Pester添加-PassThru参数后会返回包含完整测试运行统计的对象,你可以在后台Job中返回这个对象,外层接收后直接判断失败用例数即可,示例代码如下:

Describe 'Run' {
    It 'StartJobTest'  {
        $testJob = Start-Job -ScriptBlock {
            Import-Module Pester -Force
            # 用$using:前缀传递外层路径,避免Job工作目录不匹配的问题
            $testResult = Invoke-Pester -Path $using:PSScriptRoot\MyTests.Tests.ps1 -PassThru
            return $testResult
        } 
        # 等待Job完成并接收结果
        $testResult = $testJob | Receive-Job -Wait -AutoRemoveJob
        # 断言没有失败用例
        $testResult.FailedCount | Should -Be 0
    }
}

方案2:通过进程退出码判断

你之前设置的$global:PesterPreference.Run.Exit = $true是有效的,它会让Pester在测试结束后根据结果设置进程退出码(0=全部通过,非0=存在失败用例),你只需要主动获取Job的ExitCode属性判断即可,示例代码如下:

Describe 'Run' {
    It 'StartJobTest'  {
        $testJob = Start-Job -ScriptBlock {
            $global:PesterPreference.Run.Exit = $true
            Invoke-Pester $using:PSScriptRoot\MyTests.Tests.ps1
        } 
        # 等待Job运行结束
        Wait-Job $testJob | Out-Null
        # 断言退出码为0(全部通过)
        $testJob.ExitCode | Should -Be 0
        # 可选:打印内部测试的输出日志
        Receive-Job $testJob
        Remove-Job $testJob
    }
}

补充说明

如果你使用的是Pester 5以下的旧版本,-PassThru的返回结构和参数名略有差异,调整对应属性名即可正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 12:36:03