I’ve been playing around with pester for a few weeks and have had some success but have run into a few hurdles.
One hurdle seems to be how mocking works. I have a simple example below. There is really no purpose for this test except to act as an example of problems that I am running into.
PesterTest.ps1
function PesterTest {
$path = Get-Content '.\somepath.txt'
if (Test-Path $path){
"file does exist"
}
else {
"file does not exist"
}
}
PesterTest.Test.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
Describe "PesterTest" {
Context "Path does exist" {
Mock Get-Content {}
Mock Test-Path {$true}
It "Test-Path is valid" {
PesterTest | should be "file does exist"
}
}
}
When I run invoke-pester the test fail because I get an error “Cannot bind argument to parameter ‘Path’ because it is null.”
From my understanding Get-Content should return nothing because it is mocked, making the $path variable null. I would not think that this matters because Test-Path is mocked to return $true and it should not matter that the parameter that is passed is null via the $path variable. This assumption is not the case and I don’t understand why.
Now I can make Get-Content output some [String] data by mocking it like this
Mock Get-Content {“some content”}, the reason that this works from what I can tell is because Test-Path -Path parameter wants a string. If I mock Get-Content to return a string then it works.
This is a simple work around for this test but for other cmdlets that want an say a ADObject or a [Microsoft.Windows.ServerBackup.Commands.WBPolicy] object such as the Add-WBBackupTarget -Policy parameter this doesn’t work there is no easy way to mock that.
I would think if I mocked the Test-Path command to give an output of $true then it shouldn’t matter if in the actual function Test-Path gets passed a parameter of -Path that is null because of the previous mock of Get-Content {}.
If anyone has some Ideas, or suggestions I would appreciate it. If needed, I could post some more examples. I wanted to keep it simple, and came up with this test scenario.
Any help would be great, thanks!