2016-08-17 53 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