首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pester可以模拟异常吗?

Pester可以模拟异常吗?
EN

Stack Overflow用户
提问于 2017-08-09 00:34:56
回答 2查看 3.3K关注 0票数 10

我正在处理一些Pester测试用例,并且正在查看CodeCoverage结果。在大多数测试用例中,我们的代码包含try/catch,捕获的覆盖率为0%。下面是一个例子:

代码语言:javascript
复制
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
}

模拟Get-WmiObject返回值来测试$true条件非常简单。

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

代码语言:javascript
复制
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 -Times 1
    }
}

此测试的结果如下:

代码语言:javascript
复制
     Context Unit tests for Get-WmiObject error
      [-] Function test passes 138ms
        Expected: {False}
        But was:  { Test-Is64Bit }
        at line: 62 in .\Tests\Test-Is64Bit.Tests.ps1
        62:                             { Test-Is64Bit } | Should Be $false
Tests completed in 590ms
Tests Passed: 4 Failed: 1 Skipped: 0 Pending: 0 Inconclusive: 0

Code coverage report:
Covered 80.00 % of 10 analyzed Commands in 1 File.
Missed commands:

File             Function     Line Command
----             --------     ---- -------
Test-Is64Bit.ps1 Test-Is64Bit   38 Write-Error $_.Exception
Test-Is64Bit.ps1 Test-Is64Bit   38 Format-List -Force

有没有办法模拟Get-WmiObject抛出的异常,这样我们就可以让Pester落入陷阱,最终实现100%的代码覆盖率?

我当前的测试代码正在寻找异常

代码语言:javascript
复制
Context "Unit tests for Get-WmiObject exception" {
    # mock the Get-WmiObject cmdlet for unit testing
    Mock Get-WmiObject {
        Throw 'Some Error'
    } -ParameterFilter { $Class -And $Class -eq 'Win32_OperatingSystem' }

    It 'Get-WmiObject should throw' {
        { Get-WmiObject -Class 'Win32_OperatingSystem' } | Should Throw 'Some Error'
    }

    It "Throws exception" {
        { Test-Is64Bit } | Should Throw 'Some Error'
        Assert-MockCalled Get-WmiObject -Scope It -Exactly -Times 1
    }
}

上面的代码结果如下:

代码语言:javascript
复制
     Context Unit tests for Get-WmiObject exception
       [+] Get-WmiObject should throw 89ms
 Test-Is64Bit : System.Management.Automation.RuntimeException: Some Error At
 C:\ONESolutionFinance\Main\ReleaseManagement\PowerShell-Module\SPSNoDeps\Tests\Test-Is64Bit.Tests.ps1:66
 char:7
 +                 { Test-Is64Bit } | Should Throw 'Some Error'
 +                   ~~~~~~~~~~~~
     + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
     + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Is64Bit

       [-] Throws exception 51ms
         Expected: the expression to throw an exception with message {Some Error}, an exception was not raised, message was {}
             from line:2 char:5
             +                 Throw 'Some Error'
             +                 ~~~~~~~~~~~~~~~~~~
         at line: 66 in C:\ONESolutionFinance\Main\ReleaseManagement\PowerShell-Module\SPSNoDeps\Tests\Test-Is64Bit.Tests.ps1
         66:                             { Test-Is64Bit } | Should Throw 'Some Error'

测试$false将返回以下内容:

代码语言:javascript
复制
    Context Unit tests for Get-WmiObject exception
      [+] Get-WmiObject should throw 162ms
Test-Is64Bit : System.Management.Automation.RuntimeException: Some Error
At C:\ONESolutionFinance\Main\ReleaseManagement\PowerShell-Module\SPSNoDeps\Tests\Test-Is64Bit.Tests.ps1:66 char:5
+                 Test-Is64Bit | Should Be $false
+                 ~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Is64Bit

      [+] Throws exception 92ms
EN

回答 2

Stack Overflow用户

发布于 2017-08-09 01:13:22

是的,它可以!下面是一个例子:

代码语言:javascript
复制
Describe 'Mock an exception' {
    Mock Get-WMIObject { Throw 'some error' }

    It 'Get-WMIObject should throw' {
        {Get-WMIObject -class someclass} | Should Throw 'some error'
    }
}

我认为你的代码不能正常工作是因为:

代码语言:javascript
复制
{ Test-Is64Bit } | Should Be $false

应该是:

代码语言:javascript
复制
 { Test-Is64Bit } | Should Throw

当您使用Should Throw时,您可以在使用Should之前使用ScriptBlock { }

票数 11
EN

Stack Overflow用户

发布于 2020-04-22 20:58:01

代码语言:javascript
复制
function Test-LocalFile
{
    param (
        [string]
        $filepath
    )
    try {
        $FileInfo = get-item -Path $filepath -ErrorAction SilentlyContinue
        if ($FileInfo.getType().Name -eq "FileInfo") {
            return $true
        }
    } catch {

         Write-Error -Message "$($_.Exception.Message)"
         Throw
    }
}

下面是上面定义的函数如何处理异常的总体解决方案

代码语言:javascript
复制
Describe "Unit testing for exception handling" {
    Context "unit test showing exception"{

    #arrange
    Mock Write-Error{}
    Mock get-item  {
           Throw 'some error'
    }

    #act
    Write-Error 'some error'
    #assert
    It "test-Local FileThrows exception" {
             {Test-LocalFile -filepath test.txt}  | Should Throw 'some error'
            Assert-MockCalled get-item -Scope It -Exactly -Times 1
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45573647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档