纠缠模拟 CmdLets

Pester Mocking CmdLets

我对 Pester 中的模拟机制有疑问。我有一个要测试的脚本 Script.ps1。测试位于 Script.Tests.ps1。在 Script.ps1 我实现了以下功能:

function Start-Executable {
    param([string]$Executable)

    Start-Process $Executable
}

出于测试目的,我想模拟 Start-ProcessScript.Tests.ps1 包含以下测试。

BeforeAll{
   . $PSScriptRoot/Script.ps1
}

Describe 'Start-Executable' {
    Mock -CommandName 'Start-Process' -MockWith {return $null}
    
    It 'Start-Process is called.'{

       Start-Executable -Executable 'Test.exe'
       Assert-MockCalled 'Start-Process'
    }
}

如果我执行测试,真正的Start-Process抛出异常'Test.exe'找不到。如果我在 It-block 中移动模拟,则测试通过。我想在 Describe-block 中添加模拟(或者稍后,随着越来越多的测试被写入,在 Context-block 中)让一个模拟覆盖一系列测试。这可能吗?我做错了什么?

看起来您可能正在使用 Pester v5。因此,您的模拟需要位于 BeforeAllBeforeEach 块中。

这应该有效:

BeforeAll{
   . $PSScriptRoot/Script.ps1
}

Describe 'Start-Executable' {
    BeforeAll {
        Mock -CommandName 'Start-Process' -MockWith {return $null}
    }

    It 'Start-Process is called.'{

       Start-Executable -Executable 'Test.exe'
       Assert-MockCalled 'Start-Process'
    }
}

All code placed in the body of Describe outside of It, BeforeAll, BeforeEach, AfterAll, AfterEach will run during discovery and it's state might or might not be available to the test code, see Discovery and Run

-- https://pester-docs.netlify.app/docs/migrations/breaking-changes-in-v5