petercli
petercli

Reputation: 695

Pester does not call the mocked function - what am i doing wrong?

I want to mock a .net assembly function. I tried to wrap the .net function in a powershell function, but Pester still calls the original implementation of the function---how to fix? This is my test:

    Describe "something" {
$result =(.$SomeScript)   <--- get modules loaded in memory 
Context "Happy Path" {
    it "Call mocked method 1x" {
        Mock  MyFunc{ "" }
        $result =$result =(& $SomeScript)

In SomeScript , i have a implementation like this :

function MyFunc($param1, $param2)
{
return [namespace.class]::function($param1, $param2)
} 

Upvotes: 0

Views: 2322

Answers (2)

OCram85
OCram85

Reputation: 889

Let me help with an example:

First there is your wrapper file like this: src\Do-Somethin.ps1

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

Then lets take a look at the pester file 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"
        }
    }
}

Then finally run Invoke-Pester .\tests.

So you should get the following output:

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

Upvotes: 1

Peter
Peter

Reputation: 27944

You are make the Mock before you load the scriptfile. The result is that you override the mocked function. A solution can be is to make a module which contains the functions. Than load the module and mock the functions in the module.

Upvotes: 2

Related Questions