有没有办法在完成后处理 Pester Mock?

Is there a way to Dispose of a Pester Mock when done with it?

我在两个不同的 It '' 块中为 IIS 方法 Get-IISSite 设置了两个 Mock...

我 运行 遇到的问题是这两个它通过了,但是当我尝试做一个不使用模拟的常规测试时(它是同一个'上下文中的新 'it' ) 方法 returns 甚至在单独的 Its 中模拟。我在另一页上阅读了一些文档,表明 Mocks 可用于父级(相同上下文)

这让我有点担心,因为我希望找到一种机制来处理模拟,一旦它不再需要在 It 中恢复它。是否有必要在单独的描述和/或上下文中包含相同功能的非模拟? (看起来肯定是这样的)

代码如下:

编写了一个方法来环绕对 Get-IISSite 的空调用

### Get all IIS website collection
function IIS-SiteGetAll() {
    $sites = Get-IISSite

    if ($sites.Length -eq 0 -or $sites -eq $null) {
        throw 'No IIS Sites found, please check that IIS is installed and service is running.'
    }

    return $sites
}

测试片段

Describe 'IIS Site Methods' {
    Context 'IIS-SiteGetAll (mocked)' {

        It 'Throws error if number of sites returned is 0' {
            # Get-IISSite is the Powershell ISS command, we want it to return an empty collection
            Mock -CommandName Get-IISSite { 

                return @()                                
            }             

            { IIS-SiteGetAll } | Should Throw 

        }
        It 'Throws error if number of sites returned is $null' {
            # Get-IISSite is the Powershell ISS command, we want it to return an empty collection
            Mock -CommandName Get-IISSite { 

                return $null                               
            }             

            { IIS-SiteGetAll } | Should Throw 

        }
        It 'Returns collection of sites' { #IIS-SiteGetAll fails because it points to one of the two Mocks in the It above
            $actual = IIS-SiteGetAll

            $actual | Should -BeOfType [Microsoft.Web.Administration.Site]
            $actual.Length | Should -BeGreaterThan 0
        }
    }
    Context 'IIS-SiteGetAll' {            
        It 'Returns collection of sites' { # This separate chain exact same test passes.
            $actual = IIS-SiteGetAll

            $actual | Should BeOfType [Microsoft.Web.Administration.Site]
            $actual.Length | Should -BeGreaterThan 0
        }
    }
}

注意 powershell 有点模糊,因为如果你对第二个实际执行 GetType,它显示为 Object[],BaseType 为 System.Array(但失败)只有 [Microsoft.Web.Administration.Site]输出 class 似乎与此处的文档匹配:https://docs.microsoft.com/en-us/powershell/module/iisadministration/get-iissite?view=win10-ps

我不知道还有其他解决方法,但我必须在博客中找到答案,而不是在 Pester 的文档中。

作为 OP 所说的答案提交,这是他最终所做的:

当然,我通常不会在 It 块中创建 Mock;我会做你在这里所做的,并为它创建一个单独的 Context
您可以在 Pester 中使用一个 AfterEach 块,它会在每个 It 块之后 运行 但您需要知道如何先删除 Mock 才能使用它...