I have a PowerShell .ps1 file which contains functions at the top of the script followed by different commands calling these functions. I am using Pester to unit test my script file.
How do I mock a function that is within my PowerShell .ps1 script?
I have tried mocking the function, but I get an error saying "could not find command".
I have also tried adding an empty "dummy" function in the describe block. This doesn't give me the above error, but it is not mocking the function within the script correctly.
I have two files. One to hold the tests and another that holds the functions and calls to the functions. Below are two examples:
File1.ps1
Function Backup-Directory([switch]$IsError)
{
If($IsError)
{
Write-Error "Error"
Exit 1
}
}
Backup-Directory $true
File2.Tests.ps1
$here = (Split-Path -Parent $MyInvocation.MyCommand.Path) -replace '\\test', '\main'
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$productionFile = "$here\$sut"
Describe "File1" {
Context "When the Back-Directory outputs an error." {
# Arrange
Mock Back-Directory { }
Mock Write-Error
# Act
& $productionFile
$hasSucceeded = $?
# Assert
It "Calls Backup-Directory" {
Assert-MockCalled Backup-Directory -Exactly 1 -ParameterFilter {
$IsError -eq $true
}
}
It "Writes error message." {
Assert-MockCalled Write-Error -Exactly 1 -ParameterFilter {
$Message -eq "Error"
}
}
It "Exits with an error." {
$hasSucceeded | Should be $false
}
}
}