首页 > 解决方案 > 如何模拟使用不同参数和不同结果调用两次的命令

问题描述

我有一个我想用 Pester 测试的 PowerShell 函数:

function Install-RequiredModule (
    [string]$ModuleName,
    [string]$RepositoryName,
    [string]$ProxyUrl
    )
{
    # Errors from Install-Module are non-terminating.  They won't be caught using  
    # try - catch.  So check $Error instead.
    # Clear errors so we know if one shows up it must have been due to Install-Module.
    $Error.Clear()

    # Want to fail silently, without displaying anything in console to scare the user, 
    # because it's valid for Install-Module to fail for a user behind a proxy server.
    Install-Module -Name $ModuleName -Repository $RepositoryName `
        -ErrorAction SilentlyContinue -WarningAction SilentlyContinue

    if ($Error.Count -eq 0)
    {
        # throw 'NO error'
        return
    }

    # There was an error so try again, this time with proxy details.

    $proxyCredential = Get-Credential -Message 'Please enter credentials for proxy server'

    # No need to Silently Continue this time.  We want to see the error details.
    $Error.Clear()

    Install-Module -Name $ModuleName -Repository $RepositoryName `
        -Proxy $ProxyUrl -ProxyCredential $proxyCredential

    if ($Error.Count -gt 0)
    {
        throw $Error[0]
    }

    if (-not (Get-InstalledModule -Name $ModuleName -ErrorAction SilentlyContinue))
    {
        throw "Unknown error installing module '$ModuleName' from repository '$RepositoryName'."
    }

    Write-Output "Module '$ModuleName' successfully installed from repository '$RepositoryName'."
}

该函数可以调用两次 Install-Module。它首先尝试不使用代理凭据,就好像它可以直接访问 Internet。如果失败,它会再次尝试,这次使用代理凭据。

如何使用 Pester 测试此功能?

我在PowerShell 论坛中读到,我应该能够使用不同的参数过滤器两次模拟相同的命令。所以这就是我尝试的:

function ExecuteInstallRequiredModule ()
{
    Install-RequiredModule -ModuleName 'TestModule' -RepositoryName 'TestRepo' `
        -ProxyUrl 'http://myproxy'
}

Describe 'Install-RequiredModule' {

    $securePassword = "mypassword" | 
        ConvertTo-SecureString -asPlainText -Force
    $psCredential = New-Object System.Management.Automation.PSCredential  ('MyUserName', $securePassword)
    Mock Get-Credential { return $psCredential }

    # Want to add an error to $Error without it being written to the host.
    Mock Install-Module { Write-Error "Some error" -ErrorAction SilentlyContinue } `
        -ParameterFilter { $Name -eq  'TestModule' -and $Repository -eq 'TestRepo' -and $ErrorAction -eq 'SilentlyContinue' -and $WarningAction -eq 'SilentlyContinue'}
    Mock Install-Module { return $Null } `
        -ParameterFilter { $Name -eq  'TestModule' -and $Repository -eq 'TestRepo' -and $Proxy -eq 'http://myproxy' -and $ProxyCredential -eq $psCredential }

    Mock Get-InstalledModule { return @('Non-null text') }

    It 'attempts to install module a second time if first attempt fails' {
        ExecuteInstallRequiredModule
        #Assert-VerifiableMock
        #Assert-MockCalled Install-Module -Scope It -Times 2
    }
}

在被测函数中取消注释# throw 'NO error'我发现 $Error.Count 在第一次调用 Install-Module 后为 0 的行。因此,不会调用创建非终止错误的模拟,并且该函数在第二次调用 Install-Module 之前返回。

标签: powershellpester

解决方案


问题似乎是 Pester 阻止了对常用参数的过滤,因此您使用“ErrorAction”等会导致您的过滤器失败。

您可以在 Pester 模拟代码的第 254 行左右看到从模拟函数中删除的参数:Mock.ps1

此外,针对此删除的测试是 Pester 自己的单元测试之一(第 283 行):Mock.tests.ps1


推荐阅读