我想模拟一个.net汇编函数。我试图将.net函数包装在powershell函数中,但Pester仍然调用函数的原始实现---如何修复? 这是我的考验:
Describe "something" {
$result =(.$SomeScript) <--- get modules loaded in memory
Context "Happy Path" {
it "Call mocked method 1x" {
Mock MyFunc{ "" }
$result =$result =(& $SomeScript)
在SomeScript中,我有这样的实现:
function MyFunc($param1, $param2)
{
return [namespace.class]::function($param1, $param2)
}
答案 0 :(得分:1)
在加载脚本文件之前,您正在制作Mock。结果是您覆盖模拟的函数。解决方案可以是制作包含这些功能的模块。然后加载模块并模拟模块中的函数。
答案 1 :(得分:0)
让我举个例子来说明一下:
首先是你的包装文件:src\Do-Somethin.ps1
Function Get-Foobar() {
Return "This is a sample text"
}
然后让我们看一下pester文件tests\Do-Something.Tests.ps1
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# Keep in mind to adjust `.parent` method based on the directory level of the pester test file.
$RepoRoot = (Get-Item -Path $here).Parent.FullName
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude '.\tests\' -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
#endregion HEADER
Describe "Do-Something" {
Context "Mocking part" {
Mock Get-Foobar {
"Some mocked text"
}
It "Test1" {
$res = Get-Foobar
Write-Host $res
$res | Should Be "Some mocked text"
}
}
Context "without mocking" {
It "Test2" {
$res = Get-Foobar
Write-Host $res
$res | Should Be "This is a sample text"
}
}
}
然后最后运行Invoke-Pester .\tests
。
所以你应该得到以下输出:
Describing Do-Something
Context Mocking part
Some mocked text
[+] Test1 81ms
Context without mocking
This is a sample text
[+] Test2 105ms
Tests completed in 186ms
Passed: 2 Failed: 0 Skipped: 0 Pending: 0 Inconclusive: 0