小编Dav*_*ard的帖子

Pester可以嘲笑一个例外吗?

我正在研究一些Pester测试用例,我正在查看CodeCoverage结果.在大多数测试用例集中,我们的代码包含try/catch,我们在catch上获得0%的覆盖率.这是一个例子:

function Test-Is64Bit()
{

    $Result = $false

    try
    {
        if ((Get-WmiObject -Class "Win32_OperatingSystem").OSArchitecture -eq '64-bit')
        {
            $Result = $true
        }
    }
    catch
    {
        Write-Error $_.Exception | Format-List -Force
    }

    return $Result
}
Run Code Online (Sandbox Code Playgroud)

模拟Get-WmiObject返回值以测试$ true条件非常容易.

我已经尝试了一些想法来模拟Get-WmiObject中的异常但是在每种情况下异常都会传递到控制台而不是被Pester捕获并通过测试.以下是我提出的最好的但它仍然不起作用.

Context "Unit tests for Get-WmiObject exception" {
    # mock the Get-WmiObject cmdlet for unit testing
    Mock Get-WmiObject {
        Throw
    } -ParameterFilter { $Class -And $Class -eq 'Win32_OperatingSystem' }

    It "Function test passes" {
        { Test-Is64Bit } | Should Be $false
        Assert-MockCalled Get-WmiObject -Scope It -Exactly …
Run Code Online (Sandbox Code Playgroud)

powershell unit-testing mocking try-catch pester

8
推荐指数
1
解决办法
1656
查看次数

标签 统计

mocking ×1

pester ×1

powershell ×1

try-catch ×1

unit-testing ×1