pandemic
pandemic

Reputation: 1195

Pester Assert-MockCalled counts wrongly

writing some tests with Pester and Powershell

Code:

Import-Module Module
Import-Module Pester

InModuleScope Module{

    Describe 'Add-Patchgroup' {

    Context 'Add_server_to_group_fail' {
        Mock Add-ADGroupMember {throw [ADIdentityNotFoundException]} 
        It 'NotCorrectNamingConvention' {
            {Add-Patchgroup -ComputerName "NotExistingServer" | Should -BeLike "WARNING: Could not reach*"}
        }

        It 'CorrectNamingConventionNotExistingServer' {
            {Add-Patchgroup -ComputerName "<nameOfTheServer>" | Should -Throw}
        }

        Assert-MockCalled Add-ADGroupMember -Exactly 1

    }
}
}

and got this output:

 Context Add_server_to_group_fail
      [+] NotCorrectNamingConvention 41ms
      [+] CorrectNamingConventionNotExistingServer 5ms
      [-] Error occurred in Context block 56ms
        Expected Add-ADGroupMember in module PsLeanOps to be called 1 times exactly but was called 0 times
        25:             Assert-MockCalled Add-ADGroupMember -Exactly 1
        at <ScriptBlock>, C:\Users\a.antr01\Desktop\AddPatchGroups.Tests.ps1: line 25
        at DescribeImpl, C:\Users\a.antr01\Documents\WindowsPowerShell\Modules\pester\Functions\Describe.ps1: line 171

Why the mocked Add-ADGroupMember wasn't called? To clarify:

Module - module name

Add-Patchgroup - function in PSLeanOps

Add-ADGroupMember - AD cmdlet used in Add-Patchgroup

EDIT

Modified the code as TheIncorrigible1 said. Here is the final code:

Mock Add-ADGroupMember {throw [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]::new()} 

            It 'CorrectNamingConventionNotExistingServer' {
                {Add-Patchgroup -ComputerName "<nameOfTheServer>" -ErrorAction Stop} | Should -Throw -ExceptionType "Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException"
            }

            Assert-MockCalled Add-ADGroupMember -Exactly 1

Upvotes: 1

Views: 506

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

The problem is your assertions. They shouldn't be in scriptblocks unless you're using -Throw (you are), but even then, only the command:

It 'NotCorrectNamingConvention' {
    Add-Patchgroup -ComputerName "NotExistingServer" | Should -BeLike "WARNING: Could not reach*"
}

It 'CorrectNamingConventionNotExistingServer' {
    { Add-Patchgroup -ComputerName "ATVT1WWFYC050" } | Should -Throw
}

As an aside, do you have a using namespace statement or adding to type accelerators in your code? [ADIdentityNotFoundException] should throw a type not found exception (and presumably, be called twice since you're calling the function twice).

Upvotes: 1

Related Questions