【问题标题】:How to mock a powershell function with mandatory parameters in pester如何在纠缠中使用强制参数模拟powershell函数
【发布时间】:2018-03-24 02:41:09
【问题描述】:

这是我的代码: Testcase.ps1

function Verify_AuthenticodeSignature{
Param(
   [Parameter(Mandatory=$true)]
   [string]$PSFilePath
)
    Write-Host $PSFilePath
    if (-Not (Test-Path $PSFilePath)){
        echo "file does not exist"
        exit 1
    }

    $Status=(Get-AuthenticodeSignature -FilePath $PSFilePath).Status
    if($Status -ne "Valid"){
        echo "Script is not signed"
    } 
}
Verify_AuthenticodeSignature

Testcase.Tests.ps1:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "Testing" {

    It "Test Path"{
       Mock Test-Path{$false}
       Mock echo{}

       Verify_AuthenticodeSignature

       Assert-MockCalled echo -Times 1
       #Verify_AuthenticodeSignature -PSFilePath 'D:\abc\xyz.ps1' |should be "file does not exist"
    }       



    It "Authentication"{
        Mock Get-AuthenticodeSignature{ return "valid" }
        Mock echo{}

        Verify_AuthenticodeSignature

        Assert-MockCalled Get-AuthenticodeSignature -Times 1
        Assert-MockCalled echo -Times 1
    }

    }

在这里,我想模拟一个带有强制参数的 powershell 函数,它不会向用户询问 $PSFilePath 变量值,而是使用任何虚拟值检查模拟函数。 每当我运行 Testcase.Tests.ps1 时,它都会提示输入 $PSFilePath 值并运行源 powershell 脚本(Testcase.ps1) 我坚持这一点,任何建议都会有很大帮助。

【问题讨论】:

  • 简短回答:你不能。针对这种情况重新编写测试(查看TestDrive:\
  • 顺便说一句:从函数中直接退出脚本是一种非常糟糕的做法,这应该是控制器的工作,而不是工具。

标签: powershell powershell-3.0 powershell-4.0 pester


【解决方案1】:

TestDrive:创建一个临时文件

Describe 'Describing test' {

    it 'dummy test fail' {
         Test-Path TestDrive:\Test.log | Should Be $True 
    }

    it 'dummy test pass' {
        'some file' | Out-File TestDrive:\Test.log
         Test-Path TestDrive:\Test.log | Should Be $True 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2014-09-17
    相关资源
    最近更新 更多