I am very new to Pester and I am trying to build tests for a very small and simple function in PowerShell:
function Toggle-Notepad {
if (-not ( Get-Process notepad -ErrorAction SilentlyContinue ) )
{
Start-Process -FilePath Notepad
}
else
{
get-process notepad | stop-process
}
}
This function just starts notepad if it is not running, else if it is running it stops it.
The test that I have designed is this:
$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!"
}
}
The above tests run as expected.
How do I rewrite the Stop-Process
function so that I can specify that this version is for accepting pipeline input?
I tried this, but it is not working:
$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!"
}
}
Since the Stop-Process
function is accepting pipeline input my objective is to Mock the function similar to that, not create a general Stop-Process
function which accepts no params.
Is there any Pester expert out there who can help?