Search code examples
powershellpester

Pester InvokeVerifiable verify specific mock was called


I'm struggling a bit with the v5 Pester way of using mocks. Can anyone give me an example how I can verify that a specific mock was called via Should -InvokeVerifiable? And also how I can check that a specific mock was called n-times.

I also checked following Pester docu Should InvokeVeriable, but didn't find an answer. Here I only found an example that invokes ALL mocks.

Example:

Describe "Describe " {

    BeforeAll {
        $localPsSession = New-PSSession -ComputerName "localhost"
        # Arrange
        Mock New-PSSession { $localPsSession } -Verifiable
        Mock Remove-PSSession -Verifiable 

        # Act -> fire the function we want to test
        ...
    }

    It "Verify that Remove-PSSession was called in Act phase" {
        # Here I want to check THAT only the Remove-PSSession mock was 
        # called and NOT the New-PSSession mock.
        # Additionally I want to check that Remove-PSSession was called e.g. 3 times
        Should -InvokeVerifiable 

    }
}

Solution

  • You can use Should -Invoke -CommandName <command> to verify a specific mock versus all of those that you've marked as verifiable. You can then also use the -Times or -Exactly parameters to specify the number of times you expect that Mock to be invoked.

    For your code to work you also need to move the 'Act' part inside the It. Example below:

    Describe "PSSession Tests" {
    
        BeforeAll {
            # Arrange
            Mock New-PSSession { } -Verifiable
            Mock Remove-PSSession { } -Verifiable 
        }
    
        
        It "Verify that New-PSSession was called" {
            # Act
            $localPsSession = New-PSSession -ComputerName "localhost"
            
            # Assert
            Should -Invoke -CommandName New-PSSession -Times 1
    
        }
    }
    

    Note I changed the test so that it is for New-PSSession as that is the cmdlet that was used.

    FYI there is also Assert-MockCalled that can be used in a similar way to validate if a specific Mock is called and how many times. The new parameters on Should replace this, but Assert-MockCalled is still in Pester v5 and can also be used.