0

我想模拟一个 .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)
} 
4

2 回答 2

2

在加载脚本文件之前,您正在制作 Mock。结果是您覆盖了模拟函数。一个解决方案是制作一个包含这些功能的模块。然后加载模块并模拟模块中的功能。

于 2016-09-01T09:58:49.230 回答
1

让我举个例子:

首先是您的包装文件,如下所示: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
于 2016-11-07T15:10:36.860 回答