powershellpester

Pester not calling mocked function (Invoke-RestMethod), calling real function


Synopsis: When setting up a Mock for Invoke-RestMethod, my test is calling the real implementation, not my mock.`

I have put together the following simple sample to demonstrate the problem

All files are in the same directory

Client.psm1

class Client
{
    [string] $Query

    Client([string] $query) 
    {
        $this.Query = $query
    }


    [string] Google()
    {
        $url = "https://www.google.com/?q=$($this.Query)"
    
        $response = Invoke-RestMethod -Uri $url `
                                        -Method GET
        
        return $response                                     
    }
}

Client.Tests.ps1

using module .\Client.psm1

Describe "Client_Tests" {    

    It "Google_queryIsPopulated_ReturnsSearchResultsContainingQuery" {            
        # Arrange
        $givenQuery = "fooBar"
        $expectedResult = "fooBar"

        Mock Invoke-RestMethod { 
            $givenQuery 
        } 

        $systemUnderTest = [Client]::new($givenQuery)        
        
        # Act
        $actualResults = $systemUnderTest.Google() 

        # Assert
        $actualResults | Should -Be $expectedResult        
    }
}

The Error message I get when I run Invoke-Pester .\Client.Tests.ps1

Starting discovery in 1 files.
Discovery found 1 tests in 53ms.
Running tests.
[-] Client_Tests.Google_queryIsPopulated_ReturnsSearchResultsContainingQuery 478ms (476ms|2ms)
 Expected strings to be the same, but they were different.
 Expected length: 6
 Actual length:   54403
 Strings differ at index 0.
 Expected: 'fooBar'
 But was:  '<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content...'
            ^
 at $actualResults | Should -Be $expectedResult, C:\Users\dgleason\Downloads\example for mock invoke-restmethod\v1\Client.Tests.ps1:21
 at <ScriptBlock>, C:\Users\dgleason\Downloads\example for mock invoke-restmethod\v1\Client.Tests.ps1:21
Tests completed in 602ms
Tests Passed: 0, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0

Solution

  • Include the module name in your Mock call using the -ModuleName parameter:

    Mock Invoke-RestMethod { $givenQuery } -ModuleName Client