2
Set-Location "C:\thisDirDoesNotExist"
If(-not $?)
{
    Write-Error -Message "error"
    Exit 1
}

如何模拟命令失败?在上面的代码中,Set-Location 命令将出现非终止错误。美元?变量将被设置为 false 并且将输出错误消息并且脚本将退出。

如何模拟 Set-Location 命令来设置 $?变量为假?

4

3 回答 3

0

通常,一个产生错误的模拟,一个测试来验证你得到了错误,如下所示:

测试代码

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
于 2016-06-01T07:13:34.860 回答
0

您可以使用Throw强制任何您想要的错误。美元?之后将是 False Throw

于 2016-05-17T12:56:19.237 回答
0

你可以使用-ErrorVariable参数。在以下示例中,$locationError将在Set-Locationcmdlet 失败时设置该变量:

Set-Location "C:\" -ErrorVariable locationError
If($locationError)
{
    Write-Error -Message "error"
    Exit 1
}

现在你所要做的就是开始$locationError嘲笑$true你的失败。

于 2016-05-17T12:40:55.293 回答