我正在使用Pester测试一个PowerShell脚本,该脚本对另一个脚本进行点源。当我试图模拟点源代码的函数时,Pester拒绝使用模拟版本。当我尝试通过将函数添加到.psm1文件并使用Import-Module而不是点源来获取函数源时,我也遇到了同样的问题。
这里有一个例子,它复制了我遇到的问题。所有3个文件都在同一个文件夹中。
Foo.ps1
Function Invoke-Foo{
'Cantelope'
}Bar.ps1
function Invoke-Bar {
. .\foo.ps1
Invoke-foo
}Bar.tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"
. .\Foo.ps1
Describe "Bar" {
It "Mocks Foo" {
Mock Invoke-Foo {'Banana'}
Invoke-Bar | should be 'Banana'
}
}在模拟Invoke-Foo之后,结果应该是'Banana',但结果是:
Describing Bar
[-] Mocks Foo 36ms
Expected string length 6 but was 9. Strings differ at index 0.
Expected: {Banana}
But was: {Cantelope}
-----------^
9: Invoke-Bar | should be 'Banana'
at <ScriptBlock>, C:\Users\geinosky\Desktop\PingTest\Bar.tests.ps1: line 9如何才能让Pester正确地使用点源函数?
发布于 2016-06-24 10:48:50
Invoke-Bar显式地对文件中的Invoke-Foo进行点源代码处理,然后调用它。点源函数隐藏了其他已定义的Invoke-Foo,包括mocked。
如果我们从Invoke-Bar中删除. .\foo.ps1,那么Pester mock就可以工作了,我们得到"Banana“。
如果我们移除mock,那么所有的命令都会工作,也就是说,所有的命令都被找到了,但是我们得到的是"Cantelope“。
换句话说,如果您希望Invoke-Foo是可模拟的,那么不要在Invoke-Bar中对其进行点源代码处理。Invoke-Bar应该假定Invoke-Foo是预定义的(原始的或模拟的),并直接使用它。
https://stackoverflow.com/questions/37950757
复制相似问题