Pester Assert-MockCalled 计数错误

Pester Assert-MockCalled counts wrongly

使用 Pester 和 Powershell 编写一些测试

代码:

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

    }
}
}

得到这个输出:

 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

为什么被嘲笑的 Add-ADGroupMember 没有被 调用? 澄清一下:

Module - 模块名称

Add-Patchgroup - PSLeanOps

中的函数

Add-ADGroupMember - Add-Patchgroup

中使用的 AD cmdlet

编辑

按照TheIncorrigible1所说修改了代码。这是最终代码:

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

问题出在你的断言上。它们不应该在脚本块中,除非你使用 -Throw(你是),但即便如此,也只有命令:

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

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

顺便说一句,您的代码中是否有 using namespace 语句或添加到类型加速器? [ADIdentityNotFoundException] 应该抛出类型未找到的异常(并且可能会被调用两次,因为您调用了该函数两次)。