2016-08-17 52 views
0

我想模擬一個.net程序集函數。我試圖將.net函數包裝在powershell函數中,但Pester仍然調用函數的原始實現---如何解決? 這是我的測試: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) 
} 

回答

1

你是讓你模擬加載腳本文件之前。結果是你重寫了模擬函數。解決辦法是製作一個包含功能的模塊。比加載模塊和模擬模塊中的功能。

0

讓我用一個例子幫助:

首先,有你這樣的封裝文件:src\Do-Somethin.ps1

Function Get-Foobar() { 
    Return "This is a sample text" 
} 

然後讓我們來看看糾纏文件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