Set-Location "C:\thisDirDoesNotExist"
If(-not $?)
{
Write-Error -Message "error"
Exit 1
}
如何模拟命令失败?在上面的代码中,Set-Location 命令将出现非终止错误。美元?变量将被设置为 false 并且将输出错误消息并且脚本将退出。
如何模拟 Set-Location 命令来设置 $?变量为假?
Set-Location "C:\thisDirDoesNotExist"
If(-not $?)
{
Write-Error -Message "error"
Exit 1
}
如何模拟命令失败?在上面的代码中,Set-Location 命令将出现非终止错误。美元?变量将被设置为 false 并且将输出错误消息并且脚本将退出。
如何模拟 Set-Location 命令来设置 $?变量为假?
通常,一个产生错误的模拟,一个测试来验证你得到了错误,如下所示:
Describe 'mock an error' {
Context 'terminating error' {
Mock -CommandName Set-Location -MockWith {Write-Error 'My Error' -ErrorAction 'Stop'}
it 'should throw' {
{Set-Location -Path .\foo -ErrorAction Stop} | should throw 'My Error'
}
}
Context 'non-terminating error' {
Mock -CommandName Set-Location -MockWith {Write-Error 'My Error' }
it 'should throw' {
{Set-Location -Path .\foo -ErrorVariable slError
$Global:slError=$slError} | should not throw
$global:slError.count |should be 1
$Global:slError[0].Exception.Message | should be 'My Error'
}
}
}
Describing mock an error Context terminating error [+] should throw 551ms Context non-terminating error Write-Error 'My Error' : My Error At C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Functions\Mock.ps1:1056 char:9 + & $___ScriptBlock___ @___BoundParameters___ @___ArgumentList_ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException [+] should throw 164ms
您可以使用Throw
强制任何您想要的错误。美元?之后将是 False Throw
。
你可以使用-ErrorVariable
参数。在以下示例中,$locationError
将在Set-Location
cmdlet 失败时设置该变量:
Set-Location "C:\" -ErrorVariable locationError
If($locationError)
{
Write-Error -Message "error"
Exit 1
}
现在你所要做的就是开始$locationError
嘲笑$true
你的失败。