[英]How to mock a powershell function with mandatory parameters in pester
這是我的代碼: 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:
創建一個臨時文件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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.