如何正确测试模拟CmdLet的ErrorVariable值?

3
我们正在尝试在一个 Pester 测试中检查 Invoke-CommandErrorVariable 中的值。但由于某种原因,-ErrorVariable 没有被实例化。
Describe 'test ErrorVariable' {
    Mock Invoke-Command {
        #[CmdletBinding()]
        #param (
        #    [String[]]$ComputerName,
        #    $ScriptBlock
        #)

        $ErrorId = 'NetworkPathNotFound,PSSessionStateBroken'
        $TargetObject = 'UnknownHost'
        $ErrorCategory = [System.Management.Automation.ErrorCategory]::OpenError
        $ErrorMessage = "Connecting to remote server $TargetObject failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer $TargetObject. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic."
        $Exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $ErrorMessage
        $ErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $Exception, $ErrorId, $ErrorCategory, $TargetObject

        $ErrorRecord
    }

    it 'should be green because it should contain the TargetObject' {
        Invoke-Command -ComputerName TestComputer -ScriptBlock {1} -ErrorVariable ConnectionError
        $ConnectionError.TargetObject | Should -Be 'UnknownHost'
    }
}

即使添加了[CmdletBinding()]选项,它仍然没有填充。我们在这里缺少什么?

我曾经在某个地方看到过(不记得是何时何地了...)设置“ErrorVariable”参数除非您还设置“ErrorAction”参数,否则它将不起作用。也许这里也是这种情况? - Theo
谢谢你的提示@Theo,我试了一下但没有什么区别。 - DarkLite1
1个回答

3
您应该使用Write-Error
Describe 'test ErrorVariable' {
    Mock Invoke-Command {
        $ErrorId = 'NetworkPathNotFound,PSSessionStateBroken'
        $TargetObject = 'UnknownHost'
        $ErrorCategory = [System.Management.Automation.ErrorCategory]::OpenError
        $ErrorMessage = "Connecting to remote server $TargetObject failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer $TargetObject. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic."
        $Exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $ErrorMessage

        Write-Error -ErrorId $ErrorId -TargetObject $TargetObject -Category $ErrorCategory -Message $ErrorMessage -Exception $Exception
    }

    it 'should be green because it should contain the TargetObject' {
        Invoke-Command -ComputerName TestComputer -ScriptBlock {1} -ErrorVariable ConnectionError -ErrorAction SilentlyContinue
        $ConnectionError.TargetObject | Should -Be 'UnknownHost'
    }
}

谢谢,这正是我在寻找的。 - DarkLite1
这个例子对我帮助很大,但是它有点过时了。在现代版本的Pester中,Mock需要在"It"内部或者在"BeforeEach"或"BeforeAll"子句中。我正在使用Pester v5.3进行测试。 - Jean Libera

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接