![](/img/trans.png)
[英]Pester mock error PSInvalidCastException on Azure cmdlet call
[英]How to mock a call to an exe file with Pester?
在 PowerShell 中开发脚本,我需要调用外部可执行文件 (.exe)。 目前我正在使用 TDD 方法开发此脚本,因此我需要模拟对此 .exe 文件的调用。
我试试这个:
Describe "Create-NewObject" {
Context "Create-Object" {
It "Runs" {
Mock '& "c:\temp\my.exe"' {return {$true}}
Create-Object| Should Be $true
}
}
}
我得到了这样的回应:
Describing Create-NewObject
Context Create-Object
[-] Runs 574ms
CommandNotFoundException: Could not find Command & "C:\temp\my.exe"
at Validate-Command, C:\Program Files\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 801
at Mock, C:\Program Files\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 168
at <ScriptBlock>, C:\T\Create-NewObject.tests.ps1: line 13
Tests completed in 574ms
Passed: 0 Failed: 1 Skipped: 0 Pending: 0 Inconclusive: 0
有没有办法模拟这种调用而不将它们封装在函数中?
我找到了一种方法来模拟对这个可执行文件的调用:
function Create-Object
{
$exp = '& "C:\temp\my.exe"'
Invoke-Expression -Command $exp
}
使用模拟的测试应该如下所示:
Describe "Create-NewObject" {
Context "Create-Object" {
It "Runs" {
Mock Invoke-Expression {return {$true}} -ParameterFilter {($Command -eq '& "C:\temp\my.exe"')
Create-Object| Should Be $true
}
}
}
是的,不幸的是,从 Pester 4.8.1 开始:
C:\\Windows\\System32\\cmd.exe
)cmd
)模拟它们,但请注意,在较旧的 Pester 版本中,仅针对显式使用.exe
扩展名(例如cmd.exe
)的调用调用模拟 - 请参阅此(过时的)GitHub 问题您自己的解决方法是有效的,但它涉及Invoke-Expression
,这很尴尬; 通常应避免使用Invoke-Expression
这是一个使用辅助函数Invoke-External
的解决方法,它包装外部程序的调用,并且作为一个函数,它本身可以被-ParameterFilter
,使用-ParameterFilter
按可执行路径过滤:
在您的代码中,定义Invoke-External
函数,然后使用它来调用c:\\temp\\my.exe
:
# Helper function for invoking an external utility (executable).
# The raison d'être for this function is to allow
# calls to external executables via their *full paths* to be mocked in Pester.
function Invoke-External {
param(
[Parameter(Mandatory=$true)]
[string] $LiteralPath,
[Parameter(ValueFromRemainingArguments=$true)]
$PassThruArgs
)
& $LiteralPath $PassThruArgs
}
# Call c:\temp\my.exe via invoke-External
# Note that you may pass arguments to pass the executable as usual (none here):
Invoke-External c:\temp\my.exe
然后,在 Pester 测试中模拟对c:\\temp\\my.exe
的调用:
Mock Invoke-External -ParameterFilter { $LiteralPath -eq 'c:\temp\my.exe' } `
-MockWith { $true }
注意:如果您的代码中只有一个对外部可执行文件的调用,则可以省略
-ParameterFilter
参数。
我试过这样的东西,似乎工作。
$PathToExe = 'C:\Windows\System32\wevtutil.exe'
New-Item -Path function: -Name $PathToExe -Value { ... }
Mock $PathToExe { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.