我对 Pester 很陌生,我正在尝试在 PowerShell 中为一个非常小而简单的函数构建测试:
function Toggle-Notepad {
if (-not ( Get-Process notepad -ErrorAction SilentlyContinue ) )
{
Start-Process -FilePath Notepad
}
else
{
get-process notepad | stop-process
}
}
如果记事本没有运行,这个函数只会启动它,否则如果它正在运行,它就会停止它。
我设计的测试是这样的:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"
Describe "Toggle-Notepad" {
Mock Stop-Process { "Process object passed! Stopping notepad!" }
Mock Start-Process { "Notepad is not running,starting it!" } -ParameterFilter { $Filepath -eq "Notepad" }
It "Starts notepad if it is not running" {
Toggle-Notepad | Should be "Notepad is not running,starting it!"
}
It "Stops notepad if it is running" {
Toggle-Notepad | Should be "Process object passed ! Stopping notepad!"
}
}
上述测试按预期运行。
如何重写Stop-Process
函数以便我可以指定此版本用于接受管道输入?
我试过这个,但它不工作:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"
Describe "Toggle-Notepad" {
Mock stop-process { "Process object passed ! Stopping notepad" } -ParameterFilter { $InputObject -is "System.Diagnostics.Process" }
Mock Start-Process {"Notepad is not running,starting it!"} -ParameterFilter { $Filepath -eq "Notepad" }
It "Starts notepad if it is not running" {
Toggle-Notepad | Should be "Notepad is not running,starting it!"
}
It "Stops notepad if it is running" {
Toggle-Notepad | Should be "Process object passed ! Stopping notepad!"
}
}
由于该Stop-Process
函数接受管道输入,我的目标是模拟与此类似的函数,而不是创建不Stop-Process
接受任何参数的通用函数。
有没有 Pester 专家可以提供帮助?