Pester 模拟 CmdLets
我对 Pester 中的模拟机制有疑问。我有一个想要测试的脚本 Script.ps1
。这些测试位于 Script.Tests.ps1 中。在 Script.ps1 中,我实现了以下函数:
function Start-Executable {
param([string]$Executable)
Start-Process $Executable
}
出于测试目的,我想模拟 Start-Process。 Script.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 块中,测试就会通过。我想在描述块中添加模拟(或者稍后,随着更多测试的编写,在上下文块中),让一个模拟覆盖一系列测试。这可能吗?我做错了什么?
I have question regarding to the mocking mechanism in Pester. I have a script Script.ps1
that I want to test. The tests are located in Script.Tests.ps1
. In Script.ps1
I implemented the following function:
function Start-Executable {
param([string]$Executable)
Start-Process $Executable
}
For testing purpose I want to mock Start-Process
. The Script.Tests.ps1
contains the following test.
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'
}
}
If I execute the test, the real Start-Process
throws an exception that 'Test.exe' could not be found. If I move the mock in the It-block, the test passes. I would like to add the mock in the Describe-block (or later, as more tests are getting written, in the Context-block) to have one mock covering a bench of tests. Is this possible and what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您可能正在使用 Pester v5。因此,您的模拟需要位于
BeforeAll
或BeforeEach
块中。这应该有效:
It looks like you're probably using Pester v5. As such your mock needs to be in a
BeforeAll
orBeforeEach
block.This should work: