模拟命令失败

时间:2016-05-17 12:34:47

标签: unit-testing powershell pester

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

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

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

3 个答案:

答案 0 :(得分:0)

您可以使用-ErrorVariable参数。在以下示例中,$locationError cmdlet失败时将设置变量Set-Location

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

现在您要做的就是将$locationError设置为$true以模拟您的失败。

答案 1 :(得分:0)

您可以使用Throw强制执行您想要的任何错误。 $? Throw之后将为False。

答案 2 :(得分: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